Building an HTTP server
Go's standard library includes a production-grade HTTP server. No framework is needed: net/http handles routing, concurrency (every request runs in its own goroutine), HTTP/2 and TLS. In this lesson you'll build a small JSON API for a shop, step by step, and test it with curl.
Hello, web
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go! You asked for %s\n", r.URL.Path)
})
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}cd hello
go run main.go # in one terminal
curl localhost:8080/ # in another
curl localhost:8080/aboutHello from Go! You asked for / Hello from Go! You asked for /about
- A handler is a function
func(w http.ResponseWriter, r *http.Request). You read the request fromrand write the response tow. "GET /"is a pattern: the method plus a path./at the end of a pattern matches everything under it.ListenAndServeblocks forever, serving requests. It only returns on an error, whichlog.Fatalprints before exiting.
Routing with patterns
Since Go 1.22, patterns can include methods and path parameters:
mux := http.NewServeMux()
mux.HandleFunc("GET /products", listProducts) // exact path
mux.HandleFunc("GET /products/{id}", getProduct) // r.PathValue("id")
mux.HandleFunc("POST /products", createProduct)
mux.HandleFunc("DELETE /products/{id}", deleteProduct)
mux.HandleFunc("GET /static/", serveFiles) // trailing slash: everything under /static/Requests with the right path but the wrong method automatically get 405 Method Not Allowed, and unknown paths get 404.
A JSON API
Here's a complete in-memory product API. A sync.Mutex protects the map, because handlers run concurrently:
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"slices"
"strconv"
"sync"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
type Store struct {
mu sync.Mutex
products map[int]Product
nextID int
}
func (s *Store) list(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
out := make([]Product, 0, len(s.products))
for _, p := range s.products {
out = append(out, p)
}
s.mu.Unlock()
slices.SortFunc(out, func(a, b Product) int { return a.ID - b.ID })
writeJSON(w, http.StatusOK, out)
}
func (s *Store) get(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
s.mu.Lock()
p, ok := s.products[id]
s.mu.Unlock()
if !ok {
writeError(w, http.StatusNotFound, "product not found")
return
}
writeJSON(w, http.StatusOK, p)
}
func (s *Store) create(w http.ResponseWriter, r *http.Request) {
var p Product
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // refuse bodies over 1 MB
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&p); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
if err := validate(p); err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
s.mu.Lock()
s.nextID++
p.ID = s.nextID
s.products[p.ID] = p
s.mu.Unlock()
w.Header().Set("Location", "/products/"+strconv.Itoa(p.ID))
writeJSON(w, http.StatusCreated, p)
}
func validate(p Product) error {
if p.Name == "" {
return errors.New("name is required")
}
if p.Price <= 0 {
return errors.New("price must be positive")
}
return nil
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
func NewServer() http.Handler {
s := &Store{products: map[int]Product{}}
mux := http.NewServeMux()
mux.HandleFunc("GET /products", s.list)
mux.HandleFunc("GET /products/{id}", s.get)
mux.HandleFunc("POST /products", s.create)
return logRequests(mux)
}
// Middleware: a handler that wraps another handler.
func logRequests(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)
})
}
func main() {
log.Println("shop API on :8080")
log.Fatal(http.ListenAndServe(":8080", NewServer()))
}Let's try every endpoint:
cd shop
go mod init example.com/shop
go run .
# in another terminal:
curl -X POST localhost:8080/products -H 'Content-Type: application/json' -d '{"name":"Keyboard","price":49.5}'
curl -X POST localhost:8080/products -H 'Content-Type: application/json' -d '{"name":"Mouse","price":19.99}'
curl localhost:8080/products
curl localhost:8080/products/2
curl -w '%{http_code}\n' localhost:8080/products/99
curl -w '%{http_code}\n' -X POST localhost:8080/products -d '{"name":"","price":5}'
curl -w '%{http_code}\n' -X POST localhost:8080/products -d '{"nam":"typo"}'
curl -o /dev/null -w '%{http_code}\n' -X DELETE localhost:8080/products/1{"id":1,"name":"Keyboard","price":49.5}
{"id":2,"name":"Mouse","price":19.99}
[{"id":1,"name":"Keyboard","price":49.5},{"id":2,"name":"Mouse","price":19.99}]
{"id":2,"name":"Mouse","price":19.99}
{"error":"product not found"}
404
{"error":"name is required"}
422
{"error":"invalid JSON: json: unknown field \"nam\""}
400
405
shop API on :8080
POST /products
POST /products
GET /products
GET /products/2
GET /products/99
POST /products
POST /products
DELETE /products/1The last lines of output are the server's own log, written by the middleware. Points to notice:
json.NewDecoder(r.Body).Decode(&p)reads the request body;DisallowUnknownFieldsrejects typos like"nam"instead of silently ignoring them.MaxBytesReaderprotects the server from huge uploads.- Handlers return after writing an error. Forgetting that
returnand carrying on is a common bug. DELETEreturned405automatically: no route matched that method.- Middleware is just a function that takes a handler and returns a handler. Logging, authentication, CORS, compression and panic recovery are all written this way and chained:
logRequests(auth(mux)).
Production settings and graceful shutdown
http.ListenAndServe has no timeouts, so a slow client could hold a connection open forever. In production, create an http.Server with timeouts, and shut down gracefully so in-flight requests can finish when you deploy:
func main() {
srv := &http.Server{
Addr: ":8080",
Handler: NewServer(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
// Wait for Ctrl+C or SIGTERM (what Docker, Kubernetes and systemd send on stop).
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
<-ctx.Done()
log.Println("shutting down…")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil { // stop accepting, finish in-flight requests
log.Println("forced shutdown:", err)
}
}Calling other APIs: the HTTP client
The same package is also an HTTP client. Always set a timeout (the default client has none) and close the body:
client := &http.Client{Timeout: 10 * time.Second}
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/rates", nil)
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("fetch rates: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("fetch rates: status %s", resp.Status)
}
var rates map[string]float64
if err := json.NewDecoder(resp.Body).Decode(&rates); err != nil {
return fmt.Errorf("decode rates: %w", err)
}Where to go next
- Databases:
database/sqlwith a driver likepgx(PostgreSQL), orsqlc, which generates type-safe Go code from your SQL queries. - Frameworks and routers: the standard library is enough for most APIs. chi, Echo and Gin add conveniences like route groups and more middleware.
- Deploying: build one static binary (
CGO_ENABLED=0 go build) and copy it into a tinyFROM scratchor distroless Docker image, or run it as a systemd service.
Practice
- Add
DELETE /products/{id}to the shop API, returning204 No Contenton success and404if the product doesn't exist. - Add a
GET /healthendpoint that returns{"status":"ok"}. - Write middleware that adds an
X-Request-IDheader to every response. - Add
?max_price=50filtering toGET /productsusingr.URL.Query().Get("max_price").
1.What does the pattern "GET /products/{id}" match?
2.Why does the Store use a sync.Mutex?
3.What is middleware in Go?
4.Why use http.Server with timeouts instead of http.ListenAndServe in production?