HTTP service

14 cards

Review this deck
All cards in this deck

Pattern `ServeMux` (Go 1.22+)

`[METHOD ][HOST]/[PATH]`, ví dụ `GET /orders/{id}`; lấy giá trị bằng `r.PathValue("id")`

Ưu tiên pattern

pattern cụ thể hơn thắng, không phụ thuộc thứ tự đăng ký; xung đột thì panic lúc đăng ký

Path khớp, method sai

405 Method Not Allowed kèm header `Allow`; pattern `GET` khớp cả `HEAD`

Header và `WriteHeader`

đặt header trước `WriteHeader`/`Write`; sau đó `Header().Set` vô tác dụng

Đọc body JSON an toàn

`http.MaxBytesReader` giới hạn kích thước, `DisallowUnknownFields` từ chối field lạ

Middleware

`func(http.Handler) http.Handler`; recover đặt trong log để log thấy status 500

Handler `slog` tuỳ biến

override `Handle`, và cả `WithAttrs`, `WithGroup` để không mất lớp bọc

`slog.LogValuer`

kiểu có `LogValue() slog.Value` để che dữ liệu nhạy cảm khi log

Timeout của `http.Server`

zero value là không timeout; tối thiểu đặt `ReadHeaderTimeout` để chống Slowloris

`http.DefaultClient`

không có timeout; tạo `&http.Client{Timeout: ...}` một lần và dùng lại

Graceful shutdown

`signal.NotifyContext` cho SIGTERM, rồi `srv.Shutdown` với context mới từ `context.Background()` kèm timeout

`ListenAndServe` sau `Shutdown`

trả `http.ErrServerClosed` ngay; `main` phải chờ `Shutdown` xong mới thoát

`stopTimeout` trên Fargate

mặc định 30 giây, tối đa 120 giây; `ShutdownTimeout` của ứng dụng phải nhỏ hơn

Cấu hình

đọc biến môi trường một lần lúc khởi động, kiểm tra, thiếu thì fail sớm; truyền `getenv` để test

HTTP service – Flashcards – Go | Học Dev