মূল কন্টেন্টে যান
eLearner.app
মডিউল 10 · 5-এর পাঠ 5কোর্সে 50/50~18 min
মডিউল পাঠ (5/5)

মিনি-প্রকল্প: একটি HTTP সার্ভার

The net/http stdlib package is enough to build a production-ready HTTP server: routing, handlers, middleware, graceful shutdown. No framework required. For typical REST APIs this is the foundation.

Hello world

Go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "hello %s", r.URL.Path[1:])
    })
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

http.ListenAndServe blocks and only returns on error. nil as the second argument = "use the DefaultServeMux".

The handler signature

All handlers share the same signature:

Go
func(w http.ResponseWriter, r *http.Request)
  • w http.ResponseWriter — output: headers, status code, body.
  • r *http.Request — input: method, URL, headers, body, context.

Typical pattern:

Go
func ping(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodGet {
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        return
    }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK) // optional, defaults to 200
    fmt.Fprintln(w, `{"ok":true}`)
}

Routing with ServeMux

*http.ServeMux is the base router. Since Go 1.22 it supports patterns with method and path parameters:

Go
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
    id := r.PathValue("id")
    fmt.Fprintln(w, "user", id)
})
mux.HandleFunc("POST /users", createUser)

http.ListenAndServe(":8080", mux)

For more sophisticated routers (groups, integrated middleware, regex) there's chi, gorilla/mux, gin, echo. The stdlib covers 90% of cases.

Middleware as a decorator

A middleware is a function func(http.Handler) http.Handler:

Go
func logMW(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        next.ServeHTTP(w, r)
        log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
    })
}

http.ListenAndServe(":8080", logMW(mux))

To chain them: logMW(authMW(rateLimitMW(mux))). Each middleware decorates the next.

http.Server for fine control

http.ListenAndServe(addr, h) is a shortcut. For timeouts, TLS, and graceful shutdown you need to instantiate http.Server:

Go
srv := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       30 * time.Second,
    WriteTimeout:      30 * time.Second,
    IdleTimeout:       2 * time.Minute,
}
log.Fatal(srv.ListenAndServe())

Graceful shutdown with context

When the process receives SIGINT/SIGTERM, you want to finish in-flight requests before closing:

Go
ctx, stop := signal.NotifyContext(context.Background(),
    os.Interrupt, syscall.SIGTERM)
defer stop()

srv := &http.Server{Addr: ":8080", Handler: mux}
go func() {
    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        log.Fatal(err)
    }
}()

<-ctx.Done() // wait for the signal

shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
    log.Println("shutdown:", err)
}

srv.Shutdown stops accepting new connections and waits for active ones to finish (up to the deadline passed in).

Reading the JSON body

Go
type CreateUserReq struct {
    Name string `json:"name"`
}

func createUser(w http.ResponseWriter, r *http.Request) {
    var req CreateUserReq
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    // ... use req.Name
    w.WriteHeader(http.StatusCreated)
}

r.Body is an io.ReadCloser: the server closes it automatically, but json.NewDecoder does not read past the first JSON object (useful for validating input).

Exercises

ব্যায়াম#go.m10.l5.e1
প্রচেষ্টা: 0লোড হচ্ছে...

Registra l'handler hello sulla route '/' usando http.HandleFunc.

সম্পাদক লোড হচ্ছে...

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

ব্যায়াম#go.m10.l5.e2
প্রচেষ্টা: 0লোড হচ্ছে...

Avvia il server su :8080 con http.ListenAndServe e stampa l'errore se non è nil.

সম্পাদক লোড হচ্ছে...

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Quiz#go.m10.l5.e3
প্রস্তুত

Qual è la firma idiomatica di un handler HTTP in Go?

Go
func H(???) { ... }
উত্তরের বিকল্প