Lab 09: HTTP Client & Server

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Go's net/http package is a production-quality HTTP library in the standard library. It provides everything from a simple file server to a full middleware-capable HTTP router.

Step 1: Basic HTTP Server

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %s!\n", r.URL.Query().Get("name"))
}

func main() {
    http.HandleFunc("/hello", helloHandler)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Welcome to Go HTTP!")
    })
    fmt.Println("server listening on :8080")
    http.ListenAndServe(":8080", nil) // uses DefaultServeMux
}

Step 2: http.ServeMux — Custom Router

💡 Tip: Go 1.22 added method-based routing (GET /path) and path wildcards ({id}) to ServeMux.

Step 3: JSON Request/Response Handling

Step 4: Middleware Pattern

Step 5: HTTP Client

Step 6: Request Context and Headers

Step 7: Error Handling and Status Codes

Step 8: Capstone — REST API with Middleware

📸 Verified Output:

Summary

Component
Key API
Notes

Server

http.ListenAndServe(addr, handler)

nil handler → DefaultServeMux

Mux

http.NewServeMux()

Go 1.22: method routing + path params

Handler

http.HandlerFunc(func(w, r))

Implements http.Handler

Path param

r.PathValue("id")

Go 1.22 — {id} in pattern

Query params

r.URL.Query().Get("key")

Returns string

JSON response

json.NewEncoder(w).Encode(v)

Set Content-Type header first

JSON request

json.NewDecoder(r.Body).Decode(&v)

Check error

Middleware

func(http.Handler) http.Handler

Chain via Chain(h, m1, m2)

Test server

httptest.NewServer(handler)

Real TCP server for client tests

Test request

httptest.NewRequest + httptest.NewRecorder

In-memory handler tests

Last updated