Translate

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 हो रहा है।

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

आप अलग-अलग routes और URLs को handle कर सकते हैं। जैसे कि /about या /contact जैसे pages create करना। इसके लिए आप multiple routes define कर सकते हैं।

package main

import (
    "fmt"
    "net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to the Home Page!")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "This is the About Page.")
}

func main() {
    http.HandleFunc("/", homeHandler)      // Home page route
    http.HandleFunc("/about", aboutHandler) // About page route

    fmt.Println("Server is running on http://localhost:8080")
    http.ListenAndServe(":8080", nil) // Start server on port 8080
}

Explanation (व्याख्या):

हमने दो अलग-अलग routes बनाए हैं:

  • / (Home Page)
  • /about (About Page)

जब आप browser में http://localhost:8080 पर जाएंगे, आपको "Welcome to the Home Page!" दिखाई देगा। और जब आप http://localhost:8080/about पर जाएंगे, तो "This is the About Page." दिखेगा।

4. Serving Static Files (Static Files Serve करना)

Static files जैसे HTML, CSS, JavaScript, या images को serve करने के लिए आप http.FileServer का use कर सकते हैं।

package main

import (
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("./static")) // Serve files from "static" folder
    http.Handle("/", fs) // Handle root route

    http.ListenAndServe(":8080", nil) // Start server on port 8080
}

Explanation (व्याख्या):

  • http.FileServer: यह function static files serve करता है। यहां हमने "./static" directory को serve करने के लिए specify किया है।
  • http.Handle("/", fs): Root route (/) पर आने वाली सभी requests को static folder में redirect कर दिया जाएगा।

Note: इस example में, आपको अपनी Go project directory में एक "static" नाम की folder बनानी होगी, जिसमें आपके HTML, CSS या अन्य files होंगी।

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

Go में आप server को gracefully shutdown कर सकते हैं, यानी जब आप server को बंद करेंगे, तो यह पहले सभी active requests को complete करेगा और फिर shutdown होगा।

package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "time"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Server running!")
}

func main() {
    srv := &http.Server{
        Addr: ":8080",
        Handler: http.HandlerFunc(handler),
    }

    go func() {
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            fmt.Printf("Listen error: %s\n", err)
        }
    }()
    fmt.Println("Server is running on http://localhost:8080")

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt)
    <-quit 5="" :="srv.Shutdown(ctx);" cancel="" code="" ctx="" defer="" down="" err="" error:="" erver="" fmt.printf="" fmt.println="" gracefully="" hutting="" if="" n="" nil="" s="" server...="" shutdown="" stopped="" time.second="">

Explanation (व्याख्या):

  • Graceful Shutdown: जब आप Ctrl+C दबाकर server को बंद करते हैं, तो server पहले active requests को finish करेगा और फिर 5 seconds के अंदर बंद हो जाएगा।
  • signal.Notify(): यह function OS signals को capture करता है (जैसे Ctrl+C)।

Conclusion (निष्कर्ष):

Golang में HTTP server बनाना बहुत आसान और efficient है। इसकी simplicity और powerful libraries इसे web development के लिए एक बेहतरीन विकल्प बनाते हैं। हमने देखा कि कैसे एक basic server बनाया जा सकता है, routes को handle किया जा सकता है, और static files serve की जा सकती हैं। आप इस code को customize करके और advanced features जैसे authentication, middleware, और databases को भी add कर सकते हैं।

Enjoy building with Golang!

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...