Translate

How to Create a Server in Golang (Go में Server कैसे बनाएं)

How to Create a Server in Golang (Go में Server कैसे बनाएं)

Golang (Go) एक powerful और efficient programming language है, और इसकी simplicity और performance इसे web servers बनाने के लिए एक ideal choice बनाती है। इस tutorial में हम एक basic HTTP server बनाना सीखेंगे।

1. Installing Go (Go को Install करना)

सबसे पहले आपको Go programming language अपने system पर install करनी होगी। Go की official website से आप Go का latest version download और install कर सकते हैं।

Go install करने के बाद, आप यह check कर सकते हैं कि Go सही तरीके से install हुआ है या नहीं, इसके लिए terminal/command prompt में go version command चलाएं:

go version

अगर आपको Go का version दिखाई दे, तो इसका मतलब है कि Go successfully install हो गया है।

2. Creating a Basic HTTP Server (Basic HTTP Server बनाना)

Golang में HTTP server बनाना बहुत simple है। Go का net/http package हमें server create करने और HTTP requests handle करने की सुविधा देता है।

नीचे हम एक basic HTTP server का code देखेंगे:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!") // Response to be displayed in the browser
}

func main() {
    http.HandleFunc("/", handler) // Define route and assign handler function
    fmt.Println("Server is running on http://localhost:8080")
    http.ListenAndServe(":8080", nil) // Start server on port 8080
}

Code Explanation (Code की व्याख्या):

  • package main: यह Go program की entry point है।
  • import: हम fmt और net/http packages को import कर रहे हैं। fmt का उपयोग output को print करने के लिए होता है और net/http package HTTP server functionality प्रदान करता है।
  • handler function: यह function हर incoming HTTP request को handle करता है। जब भी कोई user server के root (/) पर request करता है, उसे "Hello, World!" message browser में दिखाया जाएगा।
  • http.HandleFunc(): यह function एक route define करता है। यहां हम root route (/) पर आने वाली requests को handler function में भेज रहे हैं।
  • http.ListenAndServe(":8080", nil): यह server को port 8080 पर start करता है। जब user http://localhost:8080 पर जाएगा, तो उसे response मिलेगा।

Server को चलाने के लिए, आप इस code को एक file (जैसे main.go) में save करें और terminal/command prompt में इस command को run करें:

go run main.go

अब आप browser में जाकर http://localhost:8080 पर visit कर सकते हैं और देख सकते हैं कि "Hello, World!" message display हो रहा है।

Learn More About 

-Handling Different Routes (अलग-अलग Routes को Handle करना)

-Serving Static Files (Static Files Serve करना)

-Shutting Down the Server Gracefully (Server को Gracefully Shutdown करना)


No comments:

Understanding the Meaning of "GO" in Hindi | Go in Hindi

Understanding the Meaning of "GO" in Hindi ➡ Hello and Welcome to All Our Visitors from around the world! We’re excited to hav...