Building an HTTP JSON API with net/http
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
No framework needed
Go's standard library is good enough to run a real HTTP service. Since Go 1.22 the built-in router, http.ServeMux, understands HTTP methods and path parameters, which removes the main reason many people used a third-party router. We will build a small to-do API with these endpoints:
| Method and path | Purpose |
|---|---|
GET /healthz | Health check |
GET /tasks | List tasks |
POST /tasks | Create a task |
GET /tasks/{id} | Get one task |
DELETE /tasks/{id} | Delete a task |
The complete program
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
// Store is an in-memory task store, safe for concurrent use.
type Store struct {
mu sync.Mutex
nextID int
tasks map[int]Task
}
func NewStore() *Store {
return &Store{nextID: 1, tasks: make(map[int]Task)}
}
func (s *Store) Create(title string) Task {
s.mu.Lock()
defer s.mu.Unlock()
t := Task{ID: s.nextID, Title: title}
s.tasks[t.ID] = t
s.nextID++
return t
}
func (s *Store) List() []Task {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Task, 0, len(s.tasks))
for id := 1; id < s.nextID; id++ {
if t, ok := s.tasks[id]; ok {
out = append(out, t)
}
}
return out
}
func (s *Store) Get(id int) (Task, bool) {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.tasks[id]
return t, ok
}
func (s *Store) Delete(id int) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.tasks[id]
delete(s.tasks, id)
return ok
}
type API struct {
store *Store
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
slog.Error("write response", "err", err)
}
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
func (a *API) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /tasks", a.listTasks)
mux.HandleFunc("POST /tasks", a.createTask)
mux.HandleFunc("GET /tasks/{id}", a.getTask)
mux.HandleFunc("DELETE /tasks/{id}", a.deleteTask)
return mux
}
func (a *API) listTasks(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, a.store.List())
}
func (a *API) createTask(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // limit body to 1 MB
var in struct {
Title string `json:"title"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
in.Title = strings.TrimSpace(in.Title)
if in.Title == "" {
writeError(w, http.StatusUnprocessableEntity, "title is required")
return
}
writeJSON(w, http.StatusCreated, a.store.Create(in.Title))
}
func (a *API) getTask(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
}
t, ok := a.store.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "task not found")
return
}
writeJSON(w, http.StatusOK, t)
}
func (a *API) deleteTask(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
}
if !a.store.Delete(id) {
writeError(w, http.StatusNotFound, "task not found")
return
}
w.WriteHeader(http.StatusNoContent)
}
func main() {
addr := ":8080"
if port := os.Getenv("PORT"); port != "" {
addr = ":" + port
}
api := &API{store: NewStore()}
srv := &http.Server{
Addr: addr,
Handler: api.routes(),
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
slog.Info("listening", "addr", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("server failed", "err", err)
os.Exit(1)
}
}()
<-ctx.Done()
slog.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown", "err", err)
}
}
Trying it
Save it as main.go in a module and run go run .. In another terminal:
curl -X POST localhost:8080/tasks -d '{"title":"pay electricity bill"}'
curl localhost:8080/tasks
curl localhost:8080/tasks/1
curl -X DELETE localhost:8080/tasks/1 -i
The first call returns {"id":1,"title":"pay electricity bill","done":false} with status 201. On PowerShell use curl.exe.
The parts that matter
Routing. Patterns like "GET /tasks/{id}" combine method and path. The handler reads the value with r.PathValue("id"). A request with the wrong method gets 405 Method Not Allowed automatically.
JSON. json.NewEncoder(w).Encode(v) writes a value as JSON. The struct tags set the field names. json.NewDecoder(r.Body).Decode(&in) reads the request. We use DisallowUnknownFields so that typos in a client's JSON fail loudly, and http.MaxBytesReader so that nobody can send a gigabyte and fill our memory. We return 400 for broken JSON and 422 for bad content, and errors are JSON too.
Concurrency. Every request runs in its own goroutine, so shared state must be protected. The Store uses a mutex, exactly as in the sync lesson. Without it, concurrent map writes crash the server.
Timeouts. A zero-value http.Server has no timeouts, so a slow client can hold a connection forever. Always set them, as we did.
Graceful shutdown. On Ctrl+C or SIGTERM, which is what Docker and systemd send, we call srv.Shutdown. It stops accepting new connections and waits for running requests to finish, up to ten seconds. ListenAndServe then returns http.ErrServerClosed, which is not a real failure, so we filter it out.
Logging. log/slog (Go 1.21 and later) writes structured key-value logs. For per-request logs, wrap the mux in a middleware: a function that takes a handler and returns a handler.
Testing handlers
The net/http/httptest package lets you test without opening a port:
Start a server with httptest.NewServer(api.routes()), send a request with http.Post to srv.URL+"/tasks", check that the status is 201, decode the body into a Task and compare the fields. Close the server and the response body when you are done. For handlers alone, httptest.NewRecorder() with http.NewRequest works without any network at all.
Common mistakes
- Forgetting to return after writing an error. The handler keeps going and writes a second response.
- Unexported struct fields. A lowercase field is silently skipped by the JSON package.
Try it yourself
Add a PATCH /tasks/{id} endpoint that updates the done field, with a request body like {"done": true}. Return 404 for unknown ids. Add a test for it with httptest. Then add a ?done=true filter to GET /tasks.
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
// Store is an in-memory task store, safe for concurrent use.
type Store struct {
mu sync.Mutex
nextID int
tasks map[int]Task
}
func NewStore() *Store {
return &Store{nextID: 1, tasks: make(map[int]Task)}
}
func (s *Store) Create(title string) Task {
s.mu.Lock()
defer s.mu.Unlock()
t := Task{ID: s.nextID, Title: title}
s.tasks[t.ID] = t
s.nextID++
return t
}
func (s *Store) List() []Task {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Task, 0, len(s.tasks))
for id := 1; id < s.nextID; id++ {
if t, ok := s.tasks[id]; ok {
out = append(out, t)
}
}
return out
}
func (s *Store) Get(id int) (Task, bool) {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.tasks[id]
return t, ok
}
func (s *Store) Delete(id int) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.tasks[id]
delete(s.tasks, id)
return ok
}
type API struct {
store *Store
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
slog.Error("write response", "err", err)
}
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
func (a *API) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /tasks", a.listTasks)
mux.HandleFunc("POST /tasks", a.createTask)
mux.HandleFunc("GET /tasks/{id}", a.getTask)
mux.HandleFunc("DELETE /tasks/{id}", a.deleteTask)
return mux
}
func (a *API) listTasks(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, a.store.List())
}
func (a *API) createTask(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // limit body to 1 MB
var in struct {
Title string `json:"title"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
in.Title = strings.TrimSpace(in.Title)
if in.Title == "" {
writeError(w, http.StatusUnprocessableEntity, "title is required")
return
}
writeJSON(w, http.StatusCreated, a.store.Create(in.Title))
}
func (a *API) getTask(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
}
t, ok := a.store.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "task not found")
return
}
writeJSON(w, http.StatusOK, t)
}
func (a *API) deleteTask(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
}
if !a.store.Delete(id) {
writeError(w, http.StatusNotFound, "task not found")
return
}
w.WriteHeader(http.StatusNoContent)
}
func main() {
addr := ":8080"
if port := os.Getenv("PORT"); port != "" {
addr = ":" + port
}
api := &API{store: NewStore()}
srv := &http.Server{
Addr: addr,
Handler: api.routes(),
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
slog.Info("listening", "addr", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("server failed", "err", err)
os.Exit(1)
}
}()
<-ctx.Done()
slog.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown", "err", err)
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account