Go Foundations·Clarity, then concurrency

A standard-library HTTP service

Go’s net/http package is enough for a small, dependable JSON API.

Beginner 15 min read Lesson 10 of 300 Challenge included
What you will be able to do
  • Set ReadHeaderTimeout and other server timeouts.
  • Use http.MaxBytesReader to bound request bodies.
  • Return problem-style JSON and appropriate status codes.

In plain English

Register handlers, read JSON with a limit, validate, and write a status code before the body. Use server timeouts and graceful shutdown. Keep handlers thin and put business rules in functions you can test.

main.goGo
package main

import (
    "encoding/json"
    "net/http"
    "time"
)

func health(w http.ResponseWriter, _ *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]bool{"ok": true})
}

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

    server := &http.Server{
        Addr:              ":3000",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,
    }
    server.ListenAndServe()
}
Your turn

Add a health endpoint

Medium

Register GET /api/health and respond with JSON {"ok": true}.

GO · starter
mux := http.NewServeMux()
Check your understanding before moving on.
Knowledge checkQuestion 1

Which method bounds the size of a request body?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 10 of 300 · 0% of course