Standard Library HTTP Server in Go¶
Building web services using Go's standard library net/http package.
Implementation Details¶
- Uses
http.NewServeMux()for route registration. - Handlers accept
http.ResponseWriterand*http.Request. - Uses
encoding/jsonfor request/response serialization.
// Fundamentals learning: Bare minimum HTTP Server using Go's standard library.
// To run: go run basics_learning/1_basic_http/main.go
// Then open your browser at http://localhost:8080/hello
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
// In Python (FastAPI):
// @app.get("/hello")
// def say_hello():
// return "Hello from Go standard library!"
//
// In Go, endpoints are handled by functions matching the signature:
// func(http.ResponseWriter, *http.Request)
func handleHello(w http.ResponseWriter, r *http.Request) {
// WriteHeader sets the HTTP status code (default is 200 OK)
w.WriteHeader(http.StatusOK)
// w (http.ResponseWriter) implements the io.Writer interface.
// You can write text/bytes directly into it, which streams straight to the client.
fmt.Fprint(w, "Hello from the Go standard library web server!")
}
// In Python (FastAPI):
// @app.get("/json")
// def get_json():
// return {"message": "Success", "status": 200}
//
// In Go, we must explicitly marshal structs into JSON bytes and write them to the response.
func handleJSON(w http.ResponseWriter, r *http.Request) {
// 1. Set the response header to JSON (FastAPI does this automatically)
w.Header().Set("Content-Type", "application/json")
// 2. Define a local struct or map (like a Python dict)
response := struct {
Message string `json:"message"`
Status int `json:"status"`
}{
Message: "Success! You successfully parsed JSON in Go.",
Status: http.StatusOK,
}
// 3. Serialize and write the response
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(response)
if err != nil {
log.Printf("Failed to encode JSON: %v", err)
}
}
func main() {
// 1. Create a ServeMux (multiplexer/router)
// Starting in Go 1.22, you can restrict routes by HTTP method directly in the path string!
mux := http.NewServeMux()
// 2. Register routes
mux.HandleFunc("GET /hello", handleHello)
mux.HandleFunc("GET /json", handleJSON)
// 3. Configure the HTTP Server (address, router, timeouts)
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
log.Println("Starting server on :8080...")
// 4. Start the server (Listen and Serve)
// ListenAndServe starts the TCP socket listener and handles incoming requests.
// It runs forever until the server stops or crashes.
if err := server.ListenAndServe(); err != nil {
log.Fatalf("Server crashed: %v", err)
}
}