Standard Library

HTTP Clients and Servers

Build a small HTTP server and call external services safely with net/http.

What you will learn

  • write handlers and configure servers;
  • make bounded client requests and close response bodies;
  • shut a server down gracefully;

The net/http package contains both an HTTP server and an HTTP client. You can build useful network services without installing a web framework.

Your first handler

func greet(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello from Go")
}

A handler receives:

  • http.ResponseWriter, used to build the response;
  • *http.Request, containing the method, URL, headers, body, and request context.

Create a server

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /greet", greet)

    server := &http.Server{
        Addr:              ":8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,
    }

    log.Println("listening on http://localhost:8080")
    if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
        log.Fatal(err)
    }
}

Using your own ServeMux keeps dependencies explicit. A configured http.Server lets you set timeouts and later perform graceful shutdown.

Return JSON

func status(w http.ResponseWriter, r *http.Request) {
    response := struct {
        Status string `json:"status"`
    }{Status: "ok"}

    w.Header().Set("Content-Type", "application/json")
    if err := json.NewEncoder(w).Encode(response); err != nil {
        log.Println("encode response:", err)
    }
}

Set headers before calling WriteHeader or writing the body. The first body write sends status 200 OK automatically.

For an error response:

http.Error(w, "invalid request", http.StatusBadRequest)

Do not expose internal error details or secrets to clients.

Read request data carefully

Request bodies come from the network and must be treated as untrusted input. Limit body size, decode into a known struct, reject malformed data, and validate business rules separately.

r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB

decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()

var input CreateLessonRequest
if err := decoder.Decode(&input); err != nil {
    http.Error(w, "invalid JSON", http.StatusBadRequest)
    return
}

Make a client request

client := &http.Client{Timeout: 10 * time.Second}

req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
    return err
}

resp, err := client.Do(req)
if err != nil {
    return err
}
defer resp.Body.Close()

Always close a successful response body. Check the status code before decoding the response.

Reuse clients instead of creating one for every request. A client manages connection pooling internally.

Graceful shutdown

When the process receives a shutdown signal, stop accepting new requests and give active requests time to finish:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
    log.Println("shutdown:", err)
}

Production shutdown code should also coordinate background goroutines and close owned resources.

Practice

Build an in-memory lesson API with:

  • GET /lessons to return all lessons;
  • POST /lessons to validate and add one lesson;
  • JSON responses and appropriate status codes;
  • a mutex protecting the shared slice.

Summary

  • HTTP handlers translate transport details to domain operations.
  • Servers and clients need explicit size, time, and resource limits.
  • Graceful shutdown stops admission before waiting for active work.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026