Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

GO
Go
0/12 completed
Beginner
Hello GoTypes and variablesControl flowFunctions
Intermediate
Arrays, slices and mapsStructs and methodsInterfacesError handling
Advanced
GenericsGoroutines and channels
Pro
Building an HTTP serverModules, testing and tooling
Tracks / Go / Pro

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

hello/main.go
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))
}
bash
cd hello
go run main.go            # in one terminal
curl localhost:8080/       # in another
curl localhost:8080/about
Output
Hello 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 from r and write the response to w.
  • "GET /" is a pattern: the method plus a path. / at the end of a pattern matches everything under it.
  • ListenAndServe blocks forever, serving requests. It only returns on an error, which log.Fatal prints before exiting.

Routing with patterns

Since Go 1.22, patterns can include methods and path parameters:

go
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:

shop/main.go
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:

bash
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
Output
{"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/1

The 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; DisallowUnknownFields rejects typos like "nam" instead of silently ignoring them.
  • MaxBytesReader protects the server from huge uploads.
  • Handlers return after writing an error. Forgetting that return and carrying on is a common bug.
  • DELETE returned 405 automatically: 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:

go
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:

go
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/sql with a driver like pgx (PostgreSQL), or sqlc, 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 tiny FROM scratch or distroless Docker image, or run it as a systemd service.

Practice

  1. Add DELETE /products/{id} to the shop API, returning 204 No Content on success and 404 if the product doesn't exist.
  2. Add a GET /health endpoint that returns {"status":"ok"}.
  3. Write middleware that adds an X-Request-ID header to every response.
  4. Add ?max_price=50 filtering to GET /products using r.URL.Query().Get("max_price").
✎ Check your understanding

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?

← Goroutines and channels