Part 7. BackendLesson 18# go# backend# http# api

Backend — HTTP server

net/http, routing, layers, JSON, middleware, tests, graceful shutdown

Цели главы

  • Поднять HTTP-сервер и зарегистрировать эндпоинты с методами и параметрами пути.
  • Разделить приложение на слои и написать хендлер как структуру с зависимостью.
  • Читать из запроса путь, query, заголовки и JSON; отвечать JSON с правильным статусом.
  • Писать и упорядочивать middleware.
  • Тестировать хендлеры без сервера и корректно останавливать сервер.

Сеть без лишней теории

Гошный код написан, где-то есть фронтенд с кнопками и формами — как они общаются? Данные нужно передавать эффективно и надёжно, и об этом глава. Теории сетей, которую спрашивают на собеседованиях (модель OSI и прочее), здесь нет — только то, как работать с сетью именно в Go. Путь такой: простейший сервер → хендлеры и эндпоинты → структура сервиса, принятая в крупных компаниях.

net/http и роутеры

В Java для веб-сервиса нужен Spring, в Python — Django или Flask: отдельная большая библиотека поверх языка. В Go стандартная net/http настолько мощная, что сервисы иногда пишут только на ней. Фреймворки всё равно популярны:

Библиотека Что это
chi лёгкая обёртка над стандартной библиотекой; встречается в проектах чаще всего
gin самый популярный по звёздам на GitHub, полноценный фреймворк
echo, beego ещё два известных фреймворка
fiber один из самых быстрых по бенчмаркам, вдохновлён Express из мира JS

В Go даже говорят чаще не «фреймворк», а роутер (router): он направляет запросы по путям. Фреймворк — полный набор: роутер плюс работа с JSON, middleware и своя организация кода. Дальше — только net/http: разобравшись в нём, любой фреймворк выучишь за день — отличаться будет лишь синтаксис.

Первый сервер

go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, World!")
    })
    log.Println("сервер слушает :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
    // сервер: только сборка
}
bash
go run .
curl localhost:8080/hello
  • HandleFunc (handle — обрабатывать) связывает путь с функцией-обработчиком. Сигнатуру обработчика нужно запомнить: func(w http.ResponseWriter, r *http.Request).
  • Мнемоника: w — writer, сюда пишем ответ; r — запрос, его читаем.
  • ListenAndServe (serve — обслуживать) запускает сервер на порту 8080.

Эндпоинты, ServeMux и версии API

Эндпоинт (endpoint, на сленге — «ручка») — метод плюс путь: точка входа в сервер. Через одни ручки получают данные, через другие создают, меняют, удаляют. Ручки одной сущности группируют под общим путём:

Ручка Что делает
POST /api/v1/users создать пользователя
GET /api/v1/users список пользователей
GET /api/v1/users/{id} один пользователь
DELETE /api/v1/users/{id} удалить пользователя

ServeMux — мультиплексор: множество маршрутов сводится в один обработчик, который раздаёт запросы нужным функциям. Если в ListenAndServe передать nil, используется глобальный http.DefaultServeMux; в реальном коде создают свой через http.NewServeMux().

С Go 1.22 в шаблоне маршрута можно указать метод и параметры пути. Раньше приходилось делать один обработчик на все методы и внутри писать switch r.Method — отчасти поэтому и были популярны фреймворки.

go
package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /api/v1/movies/{id}", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "фильм %s", r.PathValue("id")) // параметр пути
    })
    mux.HandleFunc("GET /api/v1/movies", func(w http.ResponseWriter, r *http.Request) {
        q := r.URL.Query() // параметры после ?
        fmt.Fprintf(w, "список: limit=%s offset=%s", q.Get("limit"), q.Get("offset"))
    })
    mux.HandleFunc("DELETE /api/v1/movies/{id}", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusNoContent)
    })

    for _, req := range []*http.Request{
        httptest.NewRequest("GET", "/api/v1/movies/42", nil),
        httptest.NewRequest("GET", "/api/v1/movies?limit=10&offset=20", nil),
        httptest.NewRequest("DELETE", "/api/v1/movies/42", nil),
        httptest.NewRequest("POST", "/api/v1/movies/42", nil),
    } {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, req)
        fmt.Printf("%s %s → %d %s\n", req.Method, req.URL, rec.Code, strings.TrimSpace(rec.Body.String()))
    }
}
stdout // вывод программы
GET /api/v1/movies/42 → 200 фильм 42
GET /api/v1/movies?limit=10&offset=20 → 200 список: limit=10 offset=20
DELETE /api/v1/movies/42 → 204
POST /api/v1/movies/42 → 405 Method Not Allowed

Запросы здесь отправлены без настоящей сети, через httptest — подробнее в разделе о тестах ниже. На POST по пути, где есть только GET и DELETE, ServeMux сам ответил 405 Method Not Allowed.

Версия в пути (/api/v1) нужна, когда контракт API меняется. Одни клиенты продолжают работать с первой версией, другие переходят на /api/v2 с новыми ручками и параметрами. У многих продуктов есть только v1 — и второй может не появиться никогда, но префикс закладывают сразу.

Слои приложения

Код растёт — его делят на части с узкой зоной ответственности.

HTTP-запросhandlerразбор и проверка запроса, ответ клиентуserviceбизнес-логикаrepositoryработа с базой данныхPostgreSQL
  • Handler (handle — глагол, handler — существительное) — сущность, которая обрабатывает запросы: читает и проверяет данные, преобразует их, вызывает следующий слой и формирует ответ.
  • Service — бизнес-логика: то, что хочет бизнес. Например, выдать пользователю Premium — это не работа хендлера.
  • Repository — работа с базой данных: сохранить, найти, удалить.

Зачем делить? Чтобы одну часть можно было заменить, не задевая остальные: перейти с PostgreSQL на другую базу или принимать данные не по HTTP, а из очереди. Если бизнес-логики почти нет — данные пришли, и их надо просто сохранить, — сервисный слой опускают, и хендлер работает с репозиторием напрямую. Так дальше и сделаем.

Хендлер как структура

Хендлер оформляют структурой с зависимостями. Репозиторий передают через конструктор и описывают интерфейсом: хендлеру всё равно, что за ним — PostgreSQL, память или заглушка в тесте (16 — Интерфейсы → Дженерики, идиома «принимай интерфейсы»). Метод Routes регистрирует ручки в мультиплексоре.

go
package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strconv"
    "strings"
    "sync"
)

var ErrNotFound = errors.New("not found")

type User struct {
    ID    int64  `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

// UserRepository — то, что хендлеру нужно от хранилища.
type UserRepository interface {
    Create(name, email string) (User, error)
    GetByID(id int64) (User, error)
}

// MemoryRepo — хранилище в памяти; в главе 19 его заменит PostgreSQL.
type MemoryRepo struct {
    mu     sync.Mutex
    nextID int64
    users  map[int64]User
}

func NewMemoryRepo() *MemoryRepo {
    return &MemoryRepo{users: make(map[int64]User)}
}

func (r *MemoryRepo) Create(name, email string) (User, error) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.nextID++
    u := User{ID: r.nextID, Name: name, Email: email}
    r.users[u.ID] = u
    return u, nil
}

func (r *MemoryRepo) GetByID(id int64) (User, error) {
    r.mu.Lock()
    defer r.mu.Unlock()
    u, ok := r.users[id]
    if !ok {
        return User{}, ErrNotFound
    }
    return u, nil
}

type UserHandler struct {
    repo UserRepository
}

func NewUserHandler(repo UserRepository) *UserHandler {
    return &UserHandler{repo: repo}
}

func (h *UserHandler) Routes(mux *http.ServeMux) {
    mux.HandleFunc("POST /api/v1/users", h.CreateUser)
    mux.HandleFunc("GET /api/v1/users/{id}", h.GetUser)
}

type CreateUserRequest struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
    var req CreateUserRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        writeError(w, http.StatusBadRequest, "invalid request body")
        return
    }
    if req.Name == "" || !strings.Contains(req.Email, "@") {
        writeError(w, http.StatusBadRequest, "name and valid email are required")
        return
    }
    user, err := h.repo.Create(req.Name, req.Email)
    if err != nil {
        writeError(w, http.StatusInternalServerError, "internal error")
        return
    }
    writeJSON(w, http.StatusCreated, user)
}

func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
    if err != nil {
        writeError(w, http.StatusBadRequest, "id must be a number")
        return
    }
    user, err := h.repo.GetByID(id)
    if errors.Is(err, ErrNotFound) {
        writeError(w, http.StatusNotFound, "user not found")
        return
    }
    if err != nil {
        writeError(w, http.StatusInternalServerError, "internal error")
        return
    }
    writeJSON(w, http.StatusOK, user)
}

func writeJSON(w http.ResponseWriter, status int, data any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)           // сначала статус...
    json.NewEncoder(w).Encode(data) // ...потом тело
}

func writeError(w http.ResponseWriter, status int, message string) {
    writeJSON(w, status, map[string]string{"error": message})
}

func main() {
    mux := http.NewServeMux()
    NewUserHandler(NewMemoryRepo()).Routes(mux)

    send := func(method, target, body string) {
        req := httptest.NewRequest(method, target, strings.NewReader(body))
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, req)
        fmt.Printf("%s %s → %d %s", method, target, rec.Code, rec.Body.String())
    }
    send("POST", "/api/v1/users", `{"name":"Алексей","email":"alex@goflix.ru"}`)
    send("POST", "/api/v1/users", `{"name":`)
    send("GET", "/api/v1/users/1", "")
    send("GET", "/api/v1/users/99", "")
    send("GET", "/api/v1/users/abc", "")
}
stdout // вывод программы
POST /api/v1/users → 201 {"id":1,"name":"Алексей","email":"alex@goflix.ru"}
POST /api/v1/users → 400 {"error":"invalid request body"}
GET /api/v1/users/1 → 200 {"id":1,"name":"Алексей","email":"alex@goflix.ru"}
GET /api/v1/users/99 → 404 {"error":"user not found"}
GET /api/v1/users/abc → 400 {"error":"id must be a number"}

Что можно прочитать из запроса

Откуда Как прочитать Пример
Параметр пути r.PathValue("id") /api/v1/users/{id}
Query-параметры r.URL.Query().Get("limit") ?limit=10&offset=20 — сколько записей отдать и с какой начать
Заголовок r.Header.Get("Authorization") токен, чтобы понять, что пользователю можно
Тело (JSON) json.NewDecoder(r.Body).Decode(&req) {"name": "…", "email": "…"}

Тело читают в структуру-запрос (CreateUserRequest) с JSON-тегами (15 — Структуры → Теги), а дальше передают поля в репозиторий.

Ответ: статус до тела

Ответ формирует ResponseWriter:

  1. w.Header().Set("Content-Type", "application/json") — говорим, что отдаём JSON, а не форму или картинку.
  2. w.WriteHeader(status) — код ответа: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error.
  3. Тело — json.NewEncoder(w).Encode(data).

Чтобы не дублировать эти три строки в каждом хендлере, их выносят в writeJSON и writeError, как в примере выше. Заодно формат ответов становится единым: ошибка всегда приходит как {"error": "…"}.

Валидация

Полученные данные проверяют: имя — от 3 до 100 символов, почта — в формате почты, возраст — в разумных пределах. Удобно описывать правила тегами validate и проверять библиотекой go-playground/validator. Чтобы не повторять вызов в каждом хендлере, на проектах пишут небольшую обёртку.

go
package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required,min=3,max=100"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age,omitempty" validate:"omitempty,min=0,max=150"`
}

func main() {
    validate := validator.New()
    fmt.Println(validate.Struct(CreateUserRequest{Name: "Al", Email: "не-почта"}))
    fmt.Println(validate.Struct(CreateUserRequest{Name: "Алексей", Email: "alex@goflix.ru"}))
}
stdout // вывод программы
Key: 'CreateUserRequest.Name' Error:Field validation for 'Name' failed on the 'min' tag
Key: 'CreateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag
<nil>

Контракт API: OpenAPI и API-first

Структура User с тремя полями — простой случай. В реальности проектировать контракт — какими данными обмениваются клиент и сервер — бывает очень сложно. Контракт описывают OpenAPI-спецификацией в формате YAML: ручки, параметры, их типы и форматы, схемы объектов.

yaml
openapi: 3.0.3
info:
  title: GoFlix API
  version: 1.0.0
paths:
  /api/v1/users/{id}:
    get:
      summary: Получить пользователя
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        "200":
          description: Пользователь найден
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "404":
          description: Пользователь не найден
components:
  schemas:
    User:
      type: object
      required: [id, name, email]
      properties:
        id: { type: integer }
        name: { type: string }
        email: { type: string, format: email }

Подход API-first: сначала пишут спецификацию, а Go-код хендлеров и моделей генерируют из неё инструментами. Код гарантированно соответствует контракту, а разработчик не пишет boilerplate — повторяющийся шаблонный код — и занимается бизнес-логикой.

Middleware

Некоторые действия нужны в каждом хендлере: залогировать запрос и его длительность, проставить request ID для трейсинга, перехватить панику, проверить CORS. Их выносят в middleware — промежуточные слои. Ограничение одно: middleware принимает обработчик и возвращает обработчик — func(http.Handler) http.Handler. Слои вкладываются друг в друга, и при вызове хендлера запрос проходит через все.

  • Logging — метод, путь и сколько заняла обработка.
  • Request ID — берёт ID запроса из заголовка X-Request-Id или создаёт новый, возвращает его в ответе и кладёт в context. Трейсинг — когда запрос проходит через много сервисов, по ID его путь можно проследить при отладке.
  • Recovery — самый важный: одна паника в хендлере не должна ронять сервис. Да, в Kubernetes под перезапустится за пару секунд, но зачем, если можно перехватить панику (14 — defer, panic, recover) и ответить 500.
  • CORS — сервер разрешает запросы браузера только с определённых адресов, методов и заголовков.
go
package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "net/http/httptest"
    "os"
    "time"
)

type Middleware func(http.Handler) http.Handler

type ctxKey string // свой тип ключа: не пересечётся с ключами других пакетов

const requestIDKey ctxKey = "request_id"

var logger = log.New(os.Stdout, "", 0) // без даты — чтобы вывод был стабильным

func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        id, _ := r.Context().Value(requestIDKey).(string)
        logger.Printf("→ %s %s [%s]", r.Method, r.URL.Path, id)
        next.ServeHTTP(w, r)
        logger.Printf("← %s %s за %v", r.Method, r.URL.Path, time.Since(start).Round(time.Second))
    })
}

func RequestIDMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-Id")
        if id == "" {
            id = "req-generated" // в реальности — UUID
        }
        w.Header().Set("X-Request-Id", id)
        ctx := context.WithValue(r.Context(), requestIDKey, id)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func RecoveryMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if rec := recover(); rec != nil {
                logger.Printf("panic recovered: %v", rec)
                w.Header().Set("Content-Type", "application/json")
                w.WriteHeader(http.StatusInternalServerError)
                fmt.Fprintln(w, `{"error":"internal server error"}`)
            }
        }()
        next.ServeHTTP(w, r)
    })
}

func CORSMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "https://goflix.ru")
        w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Request-Id")
        if r.Method == http.MethodOptions {
            w.WriteHeader(http.StatusNoContent) // preflight-запрос браузера
            return
        }
        next.ServeHTTP(w, r)
    })
}

// Chain оборачивает h так, что первый middleware в списке — самый внешний.
func Chain(h http.Handler, middlewares ...Middleware) http.Handler {
    for i := len(middlewares) - 1; i >= 0; i-- {
        h = middlewares[i](h)
    }
    return h
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /movies", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Дюна, Матрица")
    })
    mux.HandleFunc("GET /panic", func(w http.ResponseWriter, r *http.Request) {
        panic("внутренний баг")
    })

    handler := Chain(mux, RecoveryMiddleware, CORSMiddleware, RequestIDMiddleware, LoggingMiddleware)

    for _, path := range []string{"/movies", "/panic"} {
        req := httptest.NewRequest("GET", path, nil)
        req.Header.Set("X-Request-Id", "abc-123")
        rec := httptest.NewRecorder()
        handler.ServeHTTP(rec, req)
        fmt.Printf("%s → %d %s", path, rec.Code, rec.Body.String())
    }
}
stdout // вывод программы
→ GET /movies [abc-123]
← GET /movies за 0s
/movies → 200 Дюна, Матрица
→ GET /panic [abc-123]
panic recovered: внутренний баг
/panic → 500 {"error":"internal server error"}

Порядок слоёв важен. Chain вызывает middleware от последнего к первому, поэтому первый в списке оказывается самым внешним: запрос проходит Recovery → CORS → RequestID → Logging → хендлер. Logging стоит после RequestID, чтобы в логе уже был ID запроса.

Часто пишут и свои middleware: авторизацию через SSO, проверку прав для всех ручек с префиксом /admin и так далее. Главное — понимать механизм, реализаций много.

Тестирование хендлеров

Чтобы протестировать хендлер, сервер поднимать не нужно. Пакет net/http/httptest даёт:

  • httptest.NewRequest(method, url, body) — конструктор тестового *http.Request;
  • httptest.NewRecorder() — подменный ResponseWriter, который просто запоминает статус, заголовки и тело.

Хендлер вызывается как обычная функция — без портов и Listen. А раз хендлер зависит от интерфейса репозитория, в тесте вместо базы подставляют заглушку (мок) с заранее заданными данными.

go
// user_handler_test.go — лежит рядом с кодом UserHandler из примера выше
package main

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)

type stubRepo struct {
    users map[int64]User
}

func (s stubRepo) Create(name, email string) (User, error) { return User{}, nil }

func (s stubRepo) GetByID(id int64) (User, error) {
    u, ok := s.users[id]
    if !ok {
        return User{}, ErrNotFound
    }
    return u, nil
}

func TestGetUser(t *testing.T) {
    mux := http.NewServeMux()
    NewUserHandler(stubRepo{users: map[int64]User{1: {ID: 1, Name: "Алексей"}}}).Routes(mux)

    tests := []struct {
        name     string
        path     string
        wantCode int
        wantBody string
    }{
        {"существующий", "/api/v1/users/1", http.StatusOK, `"name":"Алексей"`},
        {"нет такого", "/api/v1/users/2", http.StatusNotFound, "user not found"},
        {"кривой id", "/api/v1/users/abc", http.StatusBadRequest, "id must be a number"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            rec := httptest.NewRecorder()
            mux.ServeHTTP(rec, httptest.NewRequest("GET", tt.path, nil))
            if rec.Code != tt.wantCode {
                t.Fatalf("код %d, ждали %d", rec.Code, tt.wantCode)
            }
            if !strings.Contains(rec.Body.String(), tt.wantBody) {
                t.Fatalf("тело %q не содержит %q", rec.Body.String(), tt.wantBody)
            }
        })
    }
}
bash
go test -race -v ./...
text
=== RUN   TestGetUser
=== RUN   TestGetUser/существующий
=== RUN   TestGetUser/нет_такого
=== RUN   TestGetUser/кривой_id
--- PASS: TestGetUser (0.00s)
    --- PASS: TestGetUser/существующий (0.00s)
    --- PASS: TestGetUser/нет_такого (0.00s)
    --- PASS: TestGetUser/кривой_id (0.00s)
PASS

Это табличный тест из 15 — Структуры → Анонимные структуры: каждый случай — строка в слайсе, t.Run запускает его как отдельный подтест. Проверяем статус и что тело содержит нужные поля.

Graceful shutdown и таймауты

Представь: сервер обрабатывает долгие запросы — 5, 20 секунд, а то и минуты. Если в этот момент процесс убить — деплой, падение, что угодно, — клиенты получат обрыв соединения: Postman покажет socket hang up, curl — Empty reply from server. Graceful shutdown (элегантное завершение) решает это: получив сигнал остановки, сервер перестаёт принимать новые запросы, но даёт текущим доработать.

go
package main

import (
    "context"
    "errors"
    "log"
    "net/http"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(5 * time.Second) // долгий запрос
        w.Write([]byte("готово\n"))
    })

    srv := &http.Server{
        Addr:              ":8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,  // сколько ждать заголовки запроса
        ReadTimeout:       10 * time.Second, // сколько читать весь запрос
        WriteTimeout:      15 * time.Second, // сколько писать ответ
        IdleTimeout:       60 * time.Second, // сколько держать keep-alive соединение
    }

    go func() {
        log.Println("сервер запущен на :8080")
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
            log.Fatalf("ListenAndServe: %v", err)
        }
    }()

    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()
    <-ctx.Done() // ждём Ctrl+C или SIGTERM от оркестратора

    log.Println("останавливаем сервер...")
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    if err := srv.Shutdown(shutdownCtx); err != nil { // новые не принимаем, текущие дорабатывают
        log.Printf("Shutdown: %v", err)
    }
    log.Println("сервер остановлен корректно")
    // сервер: только сборка
}

Как проверить: запусти сервер, отправь curl localhost:8080/slow и сразу нажми Ctrl+C в окне сервера. Сервер напишет «останавливаем сервер...», дождётся окончания запроса, и curl получит «готово».

  • Сервер запускается в отдельной горутине, а main ждёт сигнала через signal.NotifyContext.
  • srv.Shutdown(ctx) даёт текущим запросам до 10 секунд. Большинство запросов идёт сотни миллисекунд, за 10 секунд почти все успеют; если какой-то висит 100 минут — сервер не обязан его ждать.
  • После Shutdown метод ListenAndServe возвращает http.ErrServerClosed — это не ошибка, поэтому её отфильтровывают.

Таймауты нужно ставить почти всегда: http.ListenAndServe удобен, но без таймаутов медленный клиент может держать горутину бесконечно.

Таймаут Что ограничивает
ReadHeaderTimeout ожидание заголовков запроса
ReadTimeout чтение всего запроса вместе с телом
WriteTimeout запись ответа
IdleTimeout простой keep-alive соединения между запросами

Итоги

  • Как устроена net/http: ServeMux, ResponseWriter и Request, маршруты с методами и параметрами.
  • Структура реального проекта: handler → service → repository, зависимости через интерфейсы и конструкторы.
  • Разбор запроса и единый формат JSON-ответов, валидация, контракт OpenAPI.
  • Middleware: логирование, request ID, recovery, CORS; порядок цепочки важен.
  • Тесты через httptest без сервера.
  • Graceful shutdown и таймауты — обязательная часть любого сервера.

Практика

Задание: API фильмов в памяти

По образцу UserHandler сделай API фильмов GoFlix с хранилищем в памяти:

  1. POST /api/v1/movies — создать фильм из JSON {"title": "…", "year": …}; пустое название — 400.
  2. GET /api/v1/movies?limit=&offset= — список с пагинацией; пустой список — [], а не null.
  3. DELETE /api/v1/movies/{id} — удалить; нет такого — 404, успех — 204.
  4. Хранилище потокобезопасное: sync.RWMutex.
  5. Оберни мультиплексор в middleware-цепочку и запусти сервер с graceful shutdown и таймаутами из примеров выше; проверь через curl.
решениеЭталонное решение (обработчики и хранилище)

Проверка сделана через httptest, а запуск настоящего сервера — как в разделе «Graceful shutdown».

go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "slices"
    "strconv"
    "strings"
    "sync"
)

type Movie struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Year  int    `json:"year"`
}

type MovieStore struct {
    mu     sync.RWMutex
    nextID int
    movies map[int]Movie
}

func NewMovieStore() *MovieStore { return &MovieStore{movies: make(map[int]Movie)} }

func (s *MovieStore) Add(title string, year int) Movie {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.nextID++
    m := Movie{ID: s.nextID, Title: title, Year: year}
    s.movies[m.ID] = m
    return m
}

func (s *MovieStore) List(limit, offset int) []Movie {
    s.mu.RLock()
    defer s.mu.RUnlock()
    all := make([]Movie, 0, len(s.movies))
    for _, m := range s.movies {
        all = append(all, m)
    }
    slices.SortFunc(all, func(a, b Movie) int { return a.ID - b.ID })
    if offset >= len(all) {
        return []Movie{} // пустой слайс → [] в JSON
    }
    return all[offset:min(offset+limit, len(all))]
}

func (s *MovieStore) Delete(id int) bool {
    s.mu.Lock()
    defer s.mu.Unlock()
    if _, ok := s.movies[id]; !ok {
        return false
    }
    delete(s.movies, id)
    return true
}

type MovieHandler struct{ store *MovieStore }

func (h *MovieHandler) Routes(mux *http.ServeMux) {
    mux.HandleFunc("GET /api/v1/movies", h.List)
    mux.HandleFunc("POST /api/v1/movies", h.Create)
    mux.HandleFunc("DELETE /api/v1/movies/{id}", h.Delete)
}

func (h *MovieHandler) List(w http.ResponseWriter, r *http.Request) {
    limit := queryInt(r, "limit", 10)
    offset := queryInt(r, "offset", 0)
    writeJSON(w, http.StatusOK, h.store.List(limit, offset))
}

func (h *MovieHandler) Create(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Title string `json:"title"`
        Year  int    `json:"year"`
    }
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Title == "" {
        writeJSON(w, http.StatusBadRequest, map[string]string{"error": "нужны title и year"})
        return
    }
    writeJSON(w, http.StatusCreated, h.store.Add(req.Title, req.Year))
}

func (h *MovieHandler) Delete(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil || !h.store.Delete(id) {
        writeJSON(w, http.StatusNotFound, map[string]string{"error": "фильм не найден"})
        return
    }
    w.WriteHeader(http.StatusNoContent)
}

func queryInt(r *http.Request, key string, def int) int {
    v, err := strconv.Atoi(r.URL.Query().Get(key))
    if err != nil || v < 0 {
        return def
    }
    return v
}

func writeJSON(w http.ResponseWriter, status int, data any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(data)
}

func main() {
    mux := http.NewServeMux()
    (&MovieHandler{store: NewMovieStore()}).Routes(mux)

    call := func(method, target, body string) {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body)))
        fmt.Printf("%s %s → %d %s\n", method, target, rec.Code, strings.TrimSpace(rec.Body.String()))
    }
    call("POST", "/api/v1/movies", `{"title":"Дюна","year":2021}`)
    call("POST", "/api/v1/movies", `{"title":"Матрица","year":1999}`)
    call("POST", "/api/v1/movies", `{"title":"Начало","year":2010}`)
    call("POST", "/api/v1/movies", `{"year":2010}`)
    call("GET", "/api/v1/movies?limit=2&offset=1", "")
    call("DELETE", "/api/v1/movies/2", "")
    call("DELETE", "/api/v1/movies/2", "")
    call("GET", "/api/v1/movies", "")
}
stdout // вывод программы
POST /api/v1/movies → 201 {"id":1,"title":"Дюна","year":2021}
POST /api/v1/movies → 201 {"id":2,"title":"Матрица","year":1999}
POST /api/v1/movies → 201 {"id":3,"title":"Начало","year":2010}
POST /api/v1/movies → 400 {"error":"нужны title и year"}
GET /api/v1/movies?limit=2&offset=1 → 200 [{"id":2,"title":"Матрица","year":1999},{"id":3,"title":"Начало","year":2010}]
DELETE /api/v1/movies/2 → 204
DELETE /api/v1/movies/2 → 404 {"error":"фильм не найден"}
GET /api/v1/movies → 200 [{"id":1,"title":"Дюна","year":2021},{"id":3,"title":"Начало","year":2010}]

Проверь себя

вопросКакая сигнатура у HTTP-обработчика в Go и что означают параметры?

func(w http.ResponseWriter, r *http.Request): в w пишем ответ, из r читаем запрос.

вопросЧто такое ServeMux и что изменилось в Go 1.22?

Мультиплексор: сопоставляет запросы маршрутам и вызывает нужный обработчик. С Go 1.22 в шаблоне можно указать метод и параметры пути — "GET /users/{id}" и r.PathValue("id"); на неподходящий метод мультиплексор сам отвечает 405.

вопросЗачем делить приложение на handler, service и repository?

У каждого слоя своя ответственность: транспорт, бизнес-логика, хранение. Один слой можно заменить — другую базу, другой транспорт, заглушку в тесте, — не трогая остальные.

вопросПочему WriteHeader вызывают до записи тела?

Первая запись тела неявно отправляет статус 200. Поздний WriteHeader уже ничего не изменит.

вопросЧто такое middleware и какой у него тип?

Промежуточный слой вокруг обработчика для общих задач: логи, request ID, recovery, CORS, авторизация. Тип — func(http.Handler) http.Handler.

вопросКак протестировать хендлер без запуска сервера?

Создать запрос через httptest.NewRequest, ответ записать в httptest.NewRecorder, вызвать ServeHTTP, проверить код и тело. Зависимости подменить заглушками через интерфейсы.

вопросЧто такое graceful shutdown?

Корректная остановка: получив SIGINT или SIGTERM, сервер перестаёт принимать новые запросы и даёт текущим доработать в пределах таймаута — srv.Shutdown(ctx).

вопросКакие таймауты стоит задать у http.Server?

ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout.


Ключевые выводы

  • 🌐 net/http хватает для продакшена; роутеры вроде chi лишь добавляют удобства.
  • 🛣️ С Go 1.22 маршрут — это метод и путь с параметрами: "GET /api/v1/users/{id}".
  • 🧅 Handler → service → repository; зависимости — через интерфейсы и конструкторы.
  • 📤 Ответ: заголовок Content-Type, затем статус, затем тело — единый JSON-формат ошибок.
  • 🧩 Middleware func(http.Handler) http.Handler — для логов, request ID, recovery и CORS; первый в цепочке — внешний.
  • 🧪 httptest тестирует хендлеры без сервера; моки подставляются через интерфейсы.
  • 🛑 Graceful shutdown и таймауты — обязательная часть любого сервера.

Chapter goals

  • Stand up an HTTP server and register endpoints with methods and path parameters.
  • Split an application into layers and write a handler as a struct with a dependency.
  • Read the path, query, headers, and JSON from a request; answer with JSON and the right status.
  • Write and order middleware.
  • Test handlers without a server and shut the server down correctly.

Networking without the theory overload

The Go code is written; somewhere out there is a frontend with buttons and forms — how do they talk? Data has to be transmitted efficiently and reliably, and that is what this chapter is about. There is no networking theory here (the OSI model and friends that interviews ask about) — only how to work with the network specifically in Go. The route is: the simplest server → handlers and endpoints → the service structure used at large companies.

net/http and routers

In Java a web service needs Spring, in Python — Django or Flask: a separate big library on top of the language. In Go the standard net/http is so powerful that services are sometimes written with it alone. Frameworks are still popular:

Library What it is
chi a light wrapper over the standard library; the most common in projects
gin the most starred on GitHub, a full-blown framework
echo, beego two more well-known frameworks
fiber among the fastest in benchmarks, inspired by Express from the JS world

In Go people usually say not "framework" but router: it routes requests by path. A framework is a full set: the router plus JSON handling, middleware, and its own code organization. From here on it is net/http only: once you understand it, any framework takes a day to learn — only the syntax will differ.

Your first server

go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, World!")
    })
    log.Println("server listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
    // server: compile only
}
bash
go run .
curl localhost:8080/hello
  • HandleFunc (handle — to process) binds a path to a handler function. Memorize the handler signature: func(w http.ResponseWriter, r *http.Request).
  • Mnemonic: w — writer, we write the response here; r — request, we read it.
  • ListenAndServe (serve — to serve) starts the server on port 8080.

Endpoints, ServeMux, and API versions

An endpoint is a method plus a path: an entry point into the server. Some endpoints fetch data, others create, change, or delete it. Endpoints of one entity are grouped under a common path:

Endpoint What it does
POST /api/v1/users create a user
GET /api/v1/users list users
GET /api/v1/users/{id} a single user
DELETE /api/v1/users/{id} delete a user

The ServeMux is a multiplexer: many routes collapse into one handler that hands requests to the right functions. Passing nil to ListenAndServe uses the global http.DefaultServeMux; real code creates its own via http.NewServeMux().

Since Go 1.22, a route pattern can specify the method and path parameters. Before, you had to write a single handler for all methods with a switch r.Method inside — partly why frameworks were popular.

go
package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /api/v1/movies/{id}", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "movie %s", r.PathValue("id")) // a path parameter
    })
    mux.HandleFunc("GET /api/v1/movies", func(w http.ResponseWriter, r *http.Request) {
        q := r.URL.Query() // parameters after ?
        fmt.Fprintf(w, "list: limit=%s offset=%s", q.Get("limit"), q.Get("offset"))
    })
    mux.HandleFunc("DELETE /api/v1/movies/{id}", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusNoContent)
    })

    for _, req := range []*http.Request{
        httptest.NewRequest("GET", "/api/v1/movies/42", nil),
        httptest.NewRequest("GET", "/api/v1/movies?limit=10&offset=20", nil),
        httptest.NewRequest("DELETE", "/api/v1/movies/42", nil),
        httptest.NewRequest("POST", "/api/v1/movies/42", nil),
    } {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, req)
        fmt.Printf("%s %s → %d %s\n", req.Method, req.URL, rec.Code, strings.TrimSpace(rec.Body.String()))
    }
}
stdout // program output
GET /api/v1/movies/42 → 200 movie 42
GET /api/v1/movies?limit=10&offset=20 → 200 list: limit=10 offset=20
DELETE /api/v1/movies/42 → 204
POST /api/v1/movies/42 → 405 Method Not Allowed

The requests here are sent without a real network, via httptest — details in the testing section below. For a POST to a path that only has GET and DELETE, ServeMux itself answered 405 Method Not Allowed.

A version in the path (/api/v1) is needed when the API contract changes. Some clients keep working with the first version while others move to /api/v2 with new endpoints and parameters. Many products never get past v1 — a second version may never appear — but the prefix is laid down from the start.

Application layers

The code grows, so it is split into parts with a narrow responsibility.

HTTP requesthandlerparse and validate the request, respond to the clientservicebusiness logicrepositorydatabase accessPostgreSQL
  • Handler (handle — the verb, handler — the noun) — the entity that processes requests: reads and validates data, converts it, calls the next layer, and builds the response.
  • Service — business logic: what the business wants. Granting a user Premium, for example, is not a handler's job.
  • Repository — database work: save, find, delete.

Why split? So one part can be replaced without touching the rest: switch from PostgreSQL to another database, or accept data from a queue instead of HTTP. If there is almost no business logic — the data arrived and just needs to be stored — the service layer is dropped and the handler talks to the repository directly. That is what we will do below.

A handler as a struct

A handler is made a struct with dependencies. The repository is passed in through a constructor and described with an interface: the handler does not care what is behind it — PostgreSQL, memory, or a test stub (16 — Interfaces → Generics, the "accept interfaces" idiom). The Routes method registers the endpoints on the mux.

go
package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strconv"
    "strings"
    "sync"
)

var ErrNotFound = errors.New("not found")

type User struct {
    ID    int64  `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

// UserRepository — what the handler needs from storage.
type UserRepository interface {
    Create(name, email string) (User, error)
    GetByID(id int64) (User, error)
}

// MemoryRepo — in-memory storage; PostgreSQL replaces it in chapter 19.
type MemoryRepo struct {
    mu     sync.Mutex
    nextID int64
    users  map[int64]User
}

func NewMemoryRepo() *MemoryRepo {
    return &MemoryRepo{users: make(map[int64]User)}
}

func (r *MemoryRepo) Create(name, email string) (User, error) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.nextID++
    u := User{ID: r.nextID, Name: name, Email: email}
    r.users[u.ID] = u
    return u, nil
}

func (r *MemoryRepo) GetByID(id int64) (User, error) {
    r.mu.Lock()
    defer r.mu.Unlock()
    u, ok := r.users[id]
    if !ok {
        return User{}, ErrNotFound
    }
    return u, nil
}

type UserHandler struct {
    repo UserRepository
}

func NewUserHandler(repo UserRepository) *UserHandler {
    return &UserHandler{repo: repo}
}

func (h *UserHandler) Routes(mux *http.ServeMux) {
    mux.HandleFunc("POST /api/v1/users", h.CreateUser)
    mux.HandleFunc("GET /api/v1/users/{id}", h.GetUser)
}

type CreateUserRequest struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
    var req CreateUserRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        writeError(w, http.StatusBadRequest, "invalid request body")
        return
    }
    if req.Name == "" || !strings.Contains(req.Email, "@") {
        writeError(w, http.StatusBadRequest, "name and valid email are required")
        return
    }
    user, err := h.repo.Create(req.Name, req.Email)
    if err != nil {
        writeError(w, http.StatusInternalServerError, "internal error")
        return
    }
    writeJSON(w, http.StatusCreated, user)
}

func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
    if err != nil {
        writeError(w, http.StatusBadRequest, "id must be a number")
        return
    }
    user, err := h.repo.GetByID(id)
    if errors.Is(err, ErrNotFound) {
        writeError(w, http.StatusNotFound, "user not found")
        return
    }
    if err != nil {
        writeError(w, http.StatusInternalServerError, "internal error")
        return
    }
    writeJSON(w, http.StatusOK, user)
}

func writeJSON(w http.ResponseWriter, status int, data any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)           // the status first...
    json.NewEncoder(w).Encode(data) // ...then the body
}

func writeError(w http.ResponseWriter, status int, message string) {
    writeJSON(w, status, map[string]string{"error": message})
}

func main() {
    mux := http.NewServeMux()
    NewUserHandler(NewMemoryRepo()).Routes(mux)

    send := func(method, target, body string) {
        req := httptest.NewRequest(method, target, strings.NewReader(body))
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, req)
        fmt.Printf("%s %s → %d %s", method, target, rec.Code, rec.Body.String())
    }
    send("POST", "/api/v1/users", `{"name":"Alex","email":"alex@goflix.ru"}`)
    send("POST", "/api/v1/users", `{"name":`)
    send("GET", "/api/v1/users/1", "")
    send("GET", "/api/v1/users/99", "")
    send("GET", "/api/v1/users/abc", "")
}
stdout // program output
POST /api/v1/users → 201 {"id":1,"name":"Alex","email":"alex@goflix.ru"}
POST /api/v1/users → 400 {"error":"invalid request body"}
GET /api/v1/users/1 → 200 {"id":1,"name":"Alex","email":"alex@goflix.ru"}
GET /api/v1/users/99 → 404 {"error":"user not found"}
GET /api/v1/users/abc → 400 {"error":"id must be a number"}

What you can read from a request

Source How to read it Example
Path parameter r.PathValue("id") /api/v1/users/{id}
Query parameters r.URL.Query().Get("limit") ?limit=10&offset=20 — how many records to return and where to start
Header r.Header.Get("Authorization") the token, to decide what the user may do
Body (JSON) json.NewDecoder(r.Body).Decode(&req) {"name": "…", "email": "…"}

The body is decoded into a request struct (CreateUserRequest) with JSON tags (15 — Structs → Tags), and the fields are then passed to the repository.

Response: status before body

The response is built with the ResponseWriter:

  1. w.Header().Set("Content-Type", "application/json") — say that we return JSON, not a form or an image.
  2. w.WriteHeader(status) — the response code: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error.
  3. The body — json.NewEncoder(w).Encode(data).

To avoid repeating these three lines in every handler, they are extracted into writeJSON and writeError, as in the example above. As a bonus, the response format becomes uniform: an error always arrives as {"error": "…"}.

Validation

Incoming data is checked: the name — 3 to 100 characters, the email — email-shaped, the age — within sane bounds. It is convenient to describe the rules with validate tags and check them with the go-playground/validator library. To avoid repeating the call in every handler, projects write a small wrapper.

go
package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required,min=3,max=100"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age,omitempty" validate:"omitempty,min=0,max=150"`
}

func main() {
    validate := validator.New()
    fmt.Println(validate.Struct(CreateUserRequest{Name: "Al", Email: "not-an-email"}))
    fmt.Println(validate.Struct(CreateUserRequest{Name: "Alex", Email: "alex@goflix.ru"}))
}
stdout // program output
Key: 'CreateUserRequest.Name' Error:Field validation for 'Name' failed on the 'min' tag
Key: 'CreateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag
<nil>

The API contract: OpenAPI and API-first

A User struct with three fields is the easy case. In reality, designing the contract — which data the client and the server exchange — can be very hard. The contract is described with an OpenAPI specification in YAML: endpoints, parameters, their types and formats, object schemas.

yaml
openapi: 3.0.3
info:
  title: GoFlix API
  version: 1.0.0
paths:
  /api/v1/users/{id}:
    get:
      summary: Get a user
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        "200":
          description: User found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "404":
          description: User not found
components:
  schemas:
    User:
      type: object
      required: [id, name, email]
      properties:
        id: { type: integer }
        name: { type: string }
        email: { type: string, format: email }

The API-first approach: the specification is written first, and the Go code for handlers and models is generated from it with tooling. The code is guaranteed to match the contract, and the developer does not write boilerplate — the repetitive template code — and focuses on business logic instead.

Middleware

Some actions are needed in every handler: log the request and its duration, attach a request ID for tracing, recover from panics, check CORS. They are extracted into middleware — intermediate layers. There is a single constraint: middleware takes a handler and returns a handler — func(http.Handler) http.Handler. The layers nest into each other, and when a handler is called, the request passes through all of them.

  • Logging — the method, the path, and how long processing took.
  • Request ID — takes the request ID from the X-Request-Id header or generates a new one, returns it in the response, and puts it into the context. Tracing — when a request travels through many services, the ID lets you follow its path while debugging.
  • Recovery — the most important one: a single panic in a handler must not take the service down. Yes, Kubernetes restarts the pod in seconds, but why bother if the panic can be intercepted (14 — defer, panic, recover) and answered with a 500.
  • CORS — the server allows browser requests only from specific origins, methods, and headers.
go
package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "net/http/httptest"
    "os"
    "time"
)

type Middleware func(http.Handler) http.Handler

type ctxKey string // own key type: won't clash with keys from other packages

const requestIDKey ctxKey = "request_id"

var logger = log.New(os.Stdout, "", 0) // no date — to keep the output stable

func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        id, _ := r.Context().Value(requestIDKey).(string)
        logger.Printf("→ %s %s [%s]", r.Method, r.URL.Path, id)
        next.ServeHTTP(w, r)
        logger.Printf("← %s %s in %v", r.Method, r.URL.Path, time.Since(start).Round(time.Second))
    })
}

func RequestIDMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-Id")
        if id == "" {
            id = "req-generated" // a UUID in real life
        }
        w.Header().Set("X-Request-Id", id)
        ctx := context.WithValue(r.Context(), requestIDKey, id)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func RecoveryMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if rec := recover(); rec != nil {
                logger.Printf("panic recovered: %v", rec)
                w.Header().Set("Content-Type", "application/json")
                w.WriteHeader(http.StatusInternalServerError)
                fmt.Fprintln(w, `{"error":"internal server error"}`)
            }
        }()
        next.ServeHTTP(w, r)
    })
}

func CORSMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "https://goflix.ru")
        w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Request-Id")
        if r.Method == http.MethodOptions {
            w.WriteHeader(http.StatusNoContent) // the browser's preflight request
            return
        }
        next.ServeHTTP(w, r)
    })
}

// Chain wraps h so that the first middleware in the list is the outermost.
func Chain(h http.Handler, middlewares ...Middleware) http.Handler {
    for i := len(middlewares) - 1; i >= 0; i-- {
        h = middlewares[i](h)
    }
    return h
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /movies", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Dune, The Matrix")
    })
    mux.HandleFunc("GET /panic", func(w http.ResponseWriter, r *http.Request) {
        panic("internal bug")
    })

    handler := Chain(mux, RecoveryMiddleware, CORSMiddleware, RequestIDMiddleware, LoggingMiddleware)

    for _, path := range []string{"/movies", "/panic"} {
        req := httptest.NewRequest("GET", path, nil)
        req.Header.Set("X-Request-Id", "abc-123")
        rec := httptest.NewRecorder()
        handler.ServeHTTP(rec, req)
        fmt.Printf("%s → %d %s", path, rec.Code, rec.Body.String())
    }
}
stdout // program output
→ GET /movies [abc-123]
← GET /movies in 0s
/movies → 200 Dune, The Matrix
→ GET /panic [abc-123]
panic recovered: internal bug
/panic → 500 {"error":"internal server error"}

The order of the layers matters. Chain calls the middleware from last to first, so the first in the list ends up outermost: the request goes Recovery → CORS → RequestID → Logging → handler. Logging sits after RequestID so the log already carries the request ID.

Custom middleware gets written all the time too: SSO authorization, permission checks for every route with the /admin prefix, and so on. What matters is understanding the mechanism; implementations abound.

Testing handlers

To test a handler, you do not need to start a server. The net/http/httptest package gives you:

  • httptest.NewRequest(method, url, body) — a constructor for a test *http.Request;
  • httptest.NewRecorder() — a fake ResponseWriter that simply records the status, headers, and body.

The handler is called like a regular function — no ports, no Listen. And since the handler depends on the repository interface, the test substitutes a stub (a mock) with preset data instead of the database.

go
// user_handler_test.go — lives next to the UserHandler code from the example above
package main

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)

type stubRepo struct {
    users map[int64]User
}

func (s stubRepo) Create(name, email string) (User, error) { return User{}, nil }

func (s stubRepo) GetByID(id int64) (User, error) {
    u, ok := s.users[id]
    if !ok {
        return User{}, ErrNotFound
    }
    return u, nil
}

func TestGetUser(t *testing.T) {
    mux := http.NewServeMux()
    NewUserHandler(stubRepo{users: map[int64]User{1: {ID: 1, Name: "Alex"}}}).Routes(mux)

    tests := []struct {
        name     string
        path     string
        wantCode int
        wantBody string
    }{
        {"existing", "/api/v1/users/1", http.StatusOK, `"name":"Alex"`},
        {"missing", "/api/v1/users/2", http.StatusNotFound, "user not found"},
        {"bad id", "/api/v1/users/abc", http.StatusBadRequest, "id must be a number"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            rec := httptest.NewRecorder()
            mux.ServeHTTP(rec, httptest.NewRequest("GET", tt.path, nil))
            if rec.Code != tt.wantCode {
                t.Fatalf("code %d, want %d", rec.Code, tt.wantCode)
            }
            if !strings.Contains(rec.Body.String(), tt.wantBody) {
                t.Fatalf("body %q does not contain %q", rec.Body.String(), tt.wantBody)
            }
        })
    }
}
bash
go test -race -v ./...
text
=== RUN   TestGetUser
=== RUN   TestGetUser/existing
=== RUN   TestGetUser/missing
=== RUN   TestGetUser/bad_id
--- PASS: TestGetUser (0.00s)
    --- PASS: TestGetUser/existing (0.00s)
    --- PASS: TestGetUser/missing (0.00s)
    --- PASS: TestGetUser/bad_id (0.00s)
PASS

This is the table-driven test from 15 — Structs → Anonymous structs: each case is a row in the slice, and t.Run runs it as a separate subtest. We check the status and that the body contains the needed fields.

Graceful shutdown and timeouts

Imagine: the server is processing long requests — 5, 20 seconds, even minutes. If the process is killed at that moment — a deploy, a crash, anything — clients get a dropped connection: Postman shows socket hang up, curl — Empty reply from server. Graceful shutdown solves this: on a stop signal, the server stops accepting new requests but lets the in-flight ones finish.

go
package main

import (
    "context"
    "errors"
    "log"
    "net/http"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(5 * time.Second) // a slow request
        w.Write([]byte("done\n"))
    })

    srv := &http.Server{
        Addr:              ":8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,  // how long to wait for request headers
        ReadTimeout:       10 * time.Second, // how long to read the whole request
        WriteTimeout:      15 * time.Second, // how long to write the response
        IdleTimeout:       60 * time.Second, // how long to keep a keep-alive connection
    }

    go func() {
        log.Println("server started on :8080")
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
            log.Fatalf("ListenAndServe: %v", err)
        }
    }()

    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()
    <-ctx.Done() // wait for Ctrl+C or SIGTERM from the orchestrator

    log.Println("stopping server...")
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    if err := srv.Shutdown(shutdownCtx); err != nil { // no new requests; in-flight ones finish
        log.Printf("Shutdown: %v", err)
    }
    log.Println("server stopped gracefully")
    // server: compile only
}

How to verify: start the server, send curl localhost:8080/slow, and immediately hit Ctrl+C in the server window. The server prints "stopping server...", waits for the request to finish, and curl receives "done".

  • The server runs in a separate goroutine, and main waits for the signal via signal.NotifyContext.
  • srv.Shutdown(ctx) gives in-flight requests up to 10 seconds. Most requests take hundreds of milliseconds; almost all will make it in 10 seconds — if one hangs for 100 minutes, the server is not obliged to wait.
  • After Shutdown, ListenAndServe returns http.ErrServerClosed — that is not an error, so it is filtered out.

Timeouts should be set almost always: http.ListenAndServe is convenient, but without timeouts a slow client can hold a goroutine forever.

Timeout What it bounds
ReadHeaderTimeout waiting for request headers
ReadTimeout reading the whole request, body included
WriteTimeout writing the response
IdleTimeout an idle keep-alive connection between requests

Summary

  • How net/http works: ServeMux, ResponseWriter and Request, routes with methods and parameters.
  • The structure of a real project: handler → service → repository, dependencies through interfaces and constructors.
  • Request parsing and a uniform JSON response format, validation, the OpenAPI contract.
  • Middleware: logging, request ID, recovery, CORS; the chain order matters.
  • Tests via httptest without a server.
  • Graceful shutdown and timeouts — a mandatory part of any server.

Practice

Task: an in-memory movies API

Following the UserHandler pattern, build a GoFlix movies API with in-memory storage:

  1. POST /api/v1/movies — create a movie from JSON {"title": "…", "year": …}; an empty title — 400.
  2. GET /api/v1/movies?limit=&offset= — a paginated list; an empty list is [], not null.
  3. DELETE /api/v1/movies/{id} — delete; missing — 404, success — 204.
  4. The storage is thread-safe: sync.RWMutex.
  5. Wrap the mux in a middleware chain and start the server with graceful shutdown and the timeouts from the examples above; verify with curl.
solution(handlers and storage)

The checks run through httptest; a real server starts exactly like in the "Graceful shutdown" section.

go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "slices"
    "strconv"
    "strings"
    "sync"
)

type Movie struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Year  int    `json:"year"`
}

type MovieStore struct {
    mu     sync.RWMutex
    nextID int
    movies map[int]Movie
}

func NewMovieStore() *MovieStore { return &MovieStore{movies: make(map[int]Movie)} }

func (s *MovieStore) Add(title string, year int) Movie {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.nextID++
    m := Movie{ID: s.nextID, Title: title, Year: year}
    s.movies[m.ID] = m
    return m
}

func (s *MovieStore) List(limit, offset int) []Movie {
    s.mu.RLock()
    defer s.mu.RUnlock()
    all := make([]Movie, 0, len(s.movies))
    for _, m := range s.movies {
        all = append(all, m)
    }
    slices.SortFunc(all, func(a, b Movie) int { return a.ID - b.ID })
    if offset >= len(all) {
        return []Movie{} // empty slice → [] in JSON
    }
    return all[offset:min(offset+limit, len(all))]
}

func (s *MovieStore) Delete(id int) bool {
    s.mu.Lock()
    defer s.mu.Unlock()
    if _, ok := s.movies[id]; !ok {
        return false
    }
    delete(s.movies, id)
    return true
}

type MovieHandler struct{ store *MovieStore }

func (h *MovieHandler) Routes(mux *http.ServeMux) {
    mux.HandleFunc("GET /api/v1/movies", h.List)
    mux.HandleFunc("POST /api/v1/movies", h.Create)
    mux.HandleFunc("DELETE /api/v1/movies/{id}", h.Delete)
}

func (h *MovieHandler) List(w http.ResponseWriter, r *http.Request) {
    limit := queryInt(r, "limit", 10)
    offset := queryInt(r, "offset", 0)
    writeJSON(w, http.StatusOK, h.store.List(limit, offset))
}

func (h *MovieHandler) Create(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Title string `json:"title"`
        Year  int    `json:"year"`
    }
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Title == "" {
        writeJSON(w, http.StatusBadRequest, map[string]string{"error": "title and year are required"})
        return
    }
    writeJSON(w, http.StatusCreated, h.store.Add(req.Title, req.Year))
}

func (h *MovieHandler) Delete(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil || !h.store.Delete(id) {
        writeJSON(w, http.StatusNotFound, map[string]string{"error": "movie not found"})
        return
    }
    w.WriteHeader(http.StatusNoContent)
}

func queryInt(r *http.Request, key string, def int) int {
    v, err := strconv.Atoi(r.URL.Query().Get(key))
    if err != nil || v < 0 {
        return def
    }
    return v
}

func writeJSON(w http.ResponseWriter, status int, data any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(data)
}

func main() {
    mux := http.NewServeMux()
    (&MovieHandler{store: NewMovieStore()}).Routes(mux)

    call := func(method, target, body string) {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body)))
        fmt.Printf("%s %s → %d %s\n", method, target, rec.Code, strings.TrimSpace(rec.Body.String()))
    }
    call("POST", "/api/v1/movies", `{"title":"Dune","year":2021}`)
    call("POST", "/api/v1/movies", `{"title":"The Matrix","year":1999}`)
    call("POST", "/api/v1/movies", `{"title":"Inception","year":2010}`)
    call("POST", "/api/v1/movies", `{"year":2010}`)
    call("GET", "/api/v1/movies?limit=2&offset=1", "")
    call("DELETE", "/api/v1/movies/2", "")
    call("DELETE", "/api/v1/movies/2", "")
    call("GET", "/api/v1/movies", "")
}
stdout // program output
POST /api/v1/movies → 201 {"id":1,"title":"Dune","year":2021}
POST /api/v1/movies → 201 {"id":2,"title":"The Matrix","year":1999}
POST /api/v1/movies → 201 {"id":3,"title":"Inception","year":2010}
POST /api/v1/movies → 400 {"error":"title and year are required"}
GET /api/v1/movies?limit=2&offset=1 → 200 [{"id":2,"title":"The Matrix","year":1999},{"id":3,"title":"Inception","year":2010}]
DELETE /api/v1/movies/2 → 204
DELETE /api/v1/movies/2 → 404 {"error":"movie not found"}
GET /api/v1/movies → 200 [{"id":1,"title":"Dune","year":2021},{"id":3,"title":"Inception","year":2010}]

Check yourself

questionWhat is the signature of an HTTP handler in Go, and what do the parameters mean?

func(w http.ResponseWriter, r *http.Request): we write the response into w and read the request from r.

questionWhat is ServeMux, and what changed in Go 1.22?

A multiplexer: it maps requests to routes and calls the right handler. Since Go 1.22 a pattern can name the method and path parameters — "GET /users/{id}" and r.PathValue("id"); for a wrong method the mux itself answers 405.

questionWhy split an application into handler, service, and repository?

Each layer has its own responsibility: transport, business logic, storage. One layer can be swapped — a different database, a different transport, a test stub — without touching the rest.

questionWhy is WriteHeader called before writing the body?

The first body write implicitly sends status 200. A late WriteHeader changes nothing.

questionWhat is middleware and what is its type?

An intermediate layer around a handler for cross-cutting tasks: logs, request ID, recovery, CORS, authorization. The type is func(http.Handler) http.Handler.

questionHow do you test a handler without starting a server?

Create a request with httptest.NewRequest, record the response in httptest.NewRecorder, call ServeHTTP, check the code and body. Substitute dependencies with stubs through interfaces.

questionWhat is graceful shutdown?

A clean stop: on SIGINT or SIGTERM the server stops accepting new requests and lets in-flight ones finish within a timeout — srv.Shutdown(ctx).

questionWhich timeouts should be set on an http.Server?

ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout.


Key takeaways

  • 🌐 net/http is production-ready; routers like chi only add convenience.
  • 🛣️ Since Go 1.22 a route is a method plus a path with parameters: "GET /api/v1/users/{id}".
  • 🧅 Handler → service → repository; dependencies — through interfaces and constructors.
  • 📤 Response: the Content-Type header, then the status, then the body — one uniform JSON error format.
  • 🧩 Middleware func(http.Handler) http.Handler — for logs, request ID, recovery, and CORS; the first in the chain is the outermost.
  • 🧪 httptest tests handlers without a server; mocks plug in through interfaces.
  • 🛑 Graceful shutdown and timeouts are a mandatory part of any server.
// related topics and cheatsheets