advanced
Step 13 of 15
HTTP Server Basics
Go Programming
HTTP Server Basics
Go's standard library includes a production-ready HTTP server in the net/http package — no third-party framework needed. This is one of Go's great strengths: you can build high-performance web servers using only the standard library. The HTTP server handles concurrent requests automatically using goroutines, making it naturally scalable. Understanding the http.Handler interface, multiplexers, and middleware patterns is the foundation for building web services in Go.
Basic HTTP Server
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Go server!")
}
func apiUsersHandler(w http.ResponseWriter, r *http.Request) {
users := []map[string]interface{}{
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", homeHandler)
mux.HandleFunc("GET /api/users", apiUsersHandler)
fmt.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
Middleware
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
// Chain middleware
handler := loggingMiddleware(corsMiddleware(mux))
http.ListenAndServe(":8080", handler)
Pro tip: Go 1.22+ supports method-based routing in the default mux:mux.HandleFunc("GET /users/{id}", handler). For complex routing, consider thechiorginrouters which add path parameters, middleware groups, and other features while keeping the standardhttp.Handlerinterface.
Key Takeaways
- Go's
net/httppackage provides a production-ready HTTP server with no external dependencies. - Handlers implement
http.Handleror usehttp.HandlerFuncfor simpler function-based handlers. - Middleware wraps handlers to add cross-cutting concerns like logging, auth, and CORS.
- The server handles concurrency automatically — each request runs in its own goroutine.
- Use
json.NewEncoder(w).Encode(data)for streaming JSON responses.