A REST API in Go: Planning, CRUD, Validation, Repository Pattern, DI, Pagination, Swagger
"If a handler function wants a dependency, it can bloody well ask for it as an argument. No more surprise dependencies when you’re just trying to test a single handler." — Mat Ryer، «How I write HTTP services in Go after 13 years»، وبلاگ Grafana Labs، فوریهٔ ۲۰۲۴
خلاصه (Summary): یک API کامل JSON با Go میسازیم: از برنامهریزی منبعها و URL تا رسیدگیکنندهها (Handlers)، نوعهای انتقال داده (DTOs) با بدنهٔ محدود، اعتبارسنجی (Validation)، لایهٔ سرویس (Service layer) و رابط مخزن (Repository). پاسخها کد وضعیت روشن و قالب RFC 9457 دارند. صفحهبندی Keyset با Link، Filtering و Sorting، تغییر جزئی JSON Merge Patch، ETag/If-Match برای جلوگیری از گم شدن ویرایش، Idempotency-Key برای POST، نسخهٔ /v1، قرارداد OpenAPI 3.1 با Scalar، تست httptest و تابع run با Constructor injection و Graceful shutdown هم بخشی از پروژهاند. تمرکز (Focus): برنامهریزی پروژه و مدلسازی منبعها، طراحی URL، Handlerها و Maker functionها، DTOهای درخواست و پاسخ، اعتبارسنجی با go-playground/validator یا متد دستنویس Validate()، قالب یکدست خطا و کدهای وضعیت، الگوی Repository با یک رابط برای هر تجمیع (Aggregate)، لایهٔ Service، تزریق وابستگی با Constructor و الگوی تابع run از Mat Ryer، پیکربندی از متغیرهای محیطی، صفحهبندی Offset در برابر Cursor/Keyset، فیلتر و مرتبسازی، پیوند صفحهٔ بعد، معنای PATCH و JSON Merge Patch، کنترل نسخه با ETag و If-Match، کلید Idempotency برای POST، نسخهبندی با /v1، قرارداد OpenAPI 3.1 و مقایسهٔ swaggo/swag با oapi-codegen و ogen، کلاینتهای تولیدشده و تست سرتاسری با httptest و مخزن حافظهای، خاموشی مرتب و مسیرهای سلامت، Log ساختیافته و شناسهٔ درخواست، نقطهٔ اتصال Rate limiting، ارائهٔ مستندات با Swagger UI یا Scalar و مقایسه با API Resources در Laravel. هدف یادگیری (Learning goal): یک REST service کوچک عرضه کنید که هر پاسخ آن، حتی خطا، برای کلاینت و SDK تولیدشده قابل پیشبینی باشد. بدانید هر تصمیم جلوی کدام خرابی را میگیرد: برداشت دوبارهٔ پول، گم شدن ویرایش، جابهجایی صفحه، افشای جزئیات داخلی، فاصله گرفتن Spec از اجرا یا قطع درخواست هنگام Deploy. بتوانید انتخابها را با پیشفرضهای Laravel مقایسه کنید.
این فصل پروژهٔ گروه HTTP است. الگوهای مسیر، تقدم ServeMux و Timeout سرور در net/http: Server, Client, 1.22 Routing هستند. زنجیرهسازی، CORS، فشردهسازی، Logging و Recover و Token bucket در Middlewares و Rate Limiting in Go آمدهاند. SQL مخزن، Pool و Transaction در database/sql & pgx، Fake و Mock و DI در Mocking with Interfaces & DI، تست جدولی و httptest در Testing & Benchmarking، Struct tag و Decoder در JSON, XML & Encoding، عبور ctx در context و Signal در OS Processes, Signals & Graceful Shutdown توضیح داده شدهاند. قواعد مستقل از زبان در REST API Design، API Versioning، API Idempotency و Pagination هستند؛ نگاه DDD در Repositories و API Realization: REST & GraphQL است. فصل بعد Authentication in Go است.
مبنای بررسی این صفحه، RFCهای 9457، 9110، 7396، 5789، 6585، 8288 و 6901؛ پیشنویسهای draft-ietf-httpapi-idempotency-key-header-09 و draft-ietf-httpapi-ratelimit-headers؛ OpenAPI نسخههای 3.1.0، 3.1.1 و 3.2.1؛ یادداشتهای انتشار Go 1.21 تا 1.27 و سورس Go 1.27 برای net/http، encoding/json و os/signal در go.dev است. READMEهای go-playground/validator، swaggo/swag در v1 و شاخهٔ v2، oapi-codegen، ogen، kin-openapi، huma، Scalar و Swagger UI و Go module proxy برای شمارهنسخهها هم بررسی شدهاند. پست Mat Ryer در ۲۰۲۴، آموزش Gin در go.dev، AIPهای Google به شمارهٔ 122، 132، 134، 154، 158، 160، 185 و 193، مستندات Stripe برای Pagination، Idempotency، Errors و Versioning، مستندات GitHub REST برای Pagination و API versions، JSON:API و Cursor profile آن، راهنمای Probe در Kubernetes، «No Offset» از Markus Winand، راهنمای PostgreSQL و مستندات Laravel 13 برای API Resources، Validation، Pagination، Routing و Controllers بقیهٔ منابعاند. snippetها go 1.24.0 اعلام میکنند: t.Context() و slog.DiscardHandler از 1.24، Range-over-func و Request.Pattern از 1.23 و Method pattern در ServeMux از 1.22 هستند. وابستگی github.com/go-playground/validator/v10 v10.30.1 ثابت شده، آخرین نسخه با go 1.24.0 در go.mod؛ v10.30.2 به 1.25 رفته است. کامپایل، vet و تست با -race در اجرای ثبتشده روی Go 1.27.4، macOS و Apple M4 Pro انجام شدهاند؛ transcriptهای curl آزمایشگاه از همان اجرای واقعیاند.
نقشهٔ صفحه (Page map)
| اگر دنبال این هستید | بروید به |
|---|---|
| جدولهایی برای حفظ کردن در یک دقیقه | همهچیز در یک دقیقه |
| چرا برگرداندن JSON کافی نیست | چرا وجود دارد |
| Fielding، گذار RFC 7807 به 9457، Swagger به OpenAPI 3.1 و Routing در Go 1.22 | از کجا آمده |
| پیشنویس و سرویس کامل کنار هم | Go |
| Project planning، Resource modelling و URL design | برنامهریزی API |
| Handlers، Maker function و Routes table | Handlerها |
| نوع درخواست و پاسخ (DTOs) | DTOها |
| اعتبارسنجی درخواست — request validation (go-playground/validator vs hand-written Validate()) | اعتبارسنجی |
| Error envelope و Problem Details RFC 9457 | قالب خطا |
| کد مناسب هر نتیجه (Status codes) | کدهای وضعیت |
Repository pattern و Interface per aggregate | مخزن |
| لایهٔ سرویس (Service layer) | لایهٔ سرویس |
| تزریق وابستگی و الگوی اجرا — run function pattern (Mat Ryer) | DI و run |
| پیکربندی محیطی (Configuration via env) | پیکربندی |
| صفحهبندی و پیوند صفحهٔ بعد — pagination (offset vs cursor/keyset)، Link header / next cursor | صفحهبندی |
| Filtering و Sorting | فیلتر و مرتبسازی |
| تغییر جزئی و JSON Merge Patch — partial updates PATCH | PATCH |
| کنترل نسخه، 412 و 428 — ETag and If-Match | همزمانی خوشبینانه |
| کلید تکرار ایمن — idempotency key for POST | Idempotency-Key |
| نسخهبندی — versioning (/v1) | نسخهبندی |
| قرارداد OpenAPI 3.1 و تست Drift | OpenAPI |
| مقایسهٔ تولیدکنندهها و Generated clients — swaggo/swag vs oapi-codegen vs ogen | تولیدکنندهها |
| ارائهٔ مستندات — API documentation serving (Swagger UI / Scalar) | سرو کردن مستندات |
| تست سرتاسری و مخزن حافظهای — httptest end-to-end tests، in-memory repository for tests | تست |
| Graceful shutdown و Health endpoints | خاموشی و سلامت |
| Structured logging، Request IDs و Rate limiting hook | نقاط اتصال مشاهدهپذیری |
| Decoder، پاسخ 405، Keyset SQL و بدنهٔ دقیق خطا | سازوکار |
| باگهای کلاسیک API و راهحلشان | حل مسئلههای کلاسیک |
| کدام ابزار برای کدام وضعیت | انتخاب |
| از Monolith تا سیستم توزیعشده | در معماری |
| اجرای پروژه روی ماشین خودتان | آزمایشگاه |
| مقایسه با Laravel، FormRequest و apiResource — Laravel API Resources comparison | برای توسعهدهندگان PHP/Laravel |
همهچیز در یک دقیقه (One minute)
سطح API. شش عملیات روی یک مجموعه (Collection)، بهاضافهٔ سه مسیر زیرساختی. هر ردیف در فهرست مفاهیم باز میشود.
| متد و مسیر | کاربرد | موفقیت | خطاهای معمول | تکرارپذیر (Idempotent، RFC 9110) |
|---|---|---|---|---|
GET /v1/products | فهرست، Filter، Sort و Pagination | 200 + Link: rel="next" | 400 برای Query یا Cursor نامعتبر | بله (Safe) |
POST /v1/products | ساخت | 201 + Location + ETag | 400، 409 برای SKU تکراری، 413، 415، 422 | نه؛ از Idempotency-Key استفاده کنید |
GET /v1/products/{id} | خواندن یک مورد | 200 + ETag یا 304 | 404 | بله (Safe) |
PUT /v1/products/{id} | جایگزینی فیلدهای قابل نوشتن | 200 + ETag تازه | 412، 422، 428 | بله |
PATCH /v1/products/{id} | Merge-patch چند فیلد | 200 + ETag تازه | 400، 412، 415، 422، 428 | در تعریف نه؛ با If-Match ایمن است |
DELETE /v1/products/{id} | حذف | 204 | 404، 412، 428 | بله |
GET /healthz، GET /readyz | زنده بودن (Liveness)، آمادگی (Readiness) | 200 / 503 | بله | |
GET /openapi.json، GET /docs | قرارداد و صفحهٔ مرجع | 200 | بله |
لایهها. هر لایه مسئول یک کار است و فقط به لایهٔ زیر خودش وابسته میشود.
| لایه | بسته در snippetها | چه میداند | چه نمیداند |
|---|---|---|---|
| ریشهٔ ترکیب (Composition root) | app (Run)، cmd/api | همهٔ نوعهای واقعی، Env، Flag و Signal | قواعد کسبوکار |
| مبدل HTTP (HTTP adapter) | httpapi، dto، problem | کد وضعیت، Header، JSON و DTO | SQL |
| سرویس / مورد کاربرد (Service / Use case) | service | نوعهای Domain و رابط Repository که خودش مالک آن است | HTTP و SQL |
| دامنه (Domain) | product | قواعد همیشگی و خطاهای Domain | بقیهٔ سیستم |
| ماندگاری (Persistence) | memrepo، pgrepo | ذخیرهسازی | HTTP |
Headerهایی که پروتکل را حمل میکنند.
| Header | جهت | کار | تعریفکننده |
|---|---|---|---|
Content-Type: application/problem+json | پاسخ | مشخص کردن بدنهٔ خطا | RFC 9457 |
Location | پاسخ POST | URL منبع ساختهشده | RFC 9110 |
ETag / If-Match / If-None-Match | هر دو | نسخهٔ Representation؛ خواندن و نوشتن شرطی | RFC 9110 |
Link: <…>; rel="next" | پاسخ | URL صفحهٔ بعد | RFC 8288 |
Idempotency-Key | درخواست | Retry ایمن برای POST | پیشنویس IETF؛ Stripe سالها از آن استفاده کرده |
Retry-After | پاسخ 429/503 | زمان تلاش بعدی | RFC 9110، RFC 6585 |
X-Request-ID | هر دو | پیوند Log کلاینت، Gateway و سرور | قرارداد رایج؛ RFC ندارد |
چرا وجود دارد (Why)
با net/http اولین نقطهٔ دسترسی (Endpoint) را در ده خط مینویسید. دام هم همینجاست: بدنه بیحد خوانده میشود، فیلد ناشناخته نادیده میماند، Validation با 200 {"error": "..."} جواب میگیرد، صفحهبندی با OFFSET است، PUT کورکورانه مینویسد و داده در Map سراسری میماند. در دمو کار میکند؛ زیر بار هرکدام حادثهٔ مشخصی میسازد. SDK موفقیت را از شکست تشخیص نمیدهد، برنامهٔ موبایل هنگام پیمایش یک محصول را دوباره نشان میدهد، ویرایش دو مدیر روی هم مینشیند، Retry پس از Timeout پرداخت دوم میسازد، Stack trace از خطا بیرون میریزد و Deploy درخواستهای در حال اجرا را قطع میکند.
REST API یک قرارداد (Contract) با کلاینتهایی است که کنترلشان دست شما نیست. منابع، URLها، Representationها، Status codeها، بدنهٔ خطا، Headerها و سند OpenAPI باید روشن باشند. ساختار Go هم باید از آن محافظت کند: DTO جدا از Domain، یک تابع نگاشت خطا، Contract test در برابر Spec و تست End-to-end روی زنجیرهٔ واقعی Handlerها.
| Handlerهای موردی | API طراحیشده |
|---|---|
وضعیت 200 با {"error": ...} | کد واقعی و بدنهٔ RFC 9457 |
json.Decode مستقیم در Domain struct | DTO مخصوص عملیات، بدنهٔ محدود و رد فیلد ناشناخته |
OFFSET + COUNT(*) | Keyset cursor، Header Link و بدون Total بهطور پیشفرض |
| آخرین نویسنده برنده است | ETag + If-Match و 412 هنگام تعارض |
POST تکراری منبع دوباره میسازد | Idempotency-Key پاسخ نخست را بازپخش میکند |
| مستندات پس از یک Sprint غلط میشوند | تست قرارداد OpenAPI |
Global و init() | Constructor و یک تابع run |
| فایل کمتر در روز اول | نوع و فایل بیشتر، با مسئولیت روشن |
تصویری از زندگی روزمره. میز سفارش رستوران خوب را در نظر بگیرید. منو قرارداد OpenAPI است؛ غذاها Resource هستند. برگهٔ سفارش خانههای مشخص دارد (DTO)، مسئول سفارش آن را پیش از تحویل به آشپزخانه بررسی میکند (Validation) و برای ایراد، دلیل مکتوب میدهد (Problem Details). آشپزخانه یا Service layer کاری ندارد سفارش تلفنی آمده یا از برنامه. شمارهٔ سفارش همان Idempotency-Key است: دو بار تماس دربارهٔ یک سفارش، دو غذا نمیسازد. انبار یا Repository میتواند یخچال آشپزخانهٔ آزمایشی یا سردخانهٔ واقعی باشد. هنگام بستن ابتدا در را میبندند، سپس سفارشهای در حال پخت را تمام میکنند؛ این همان Graceful shutdown است.
سه بدفهمی رایج، از همان اول
- «REST یعنی CRUD روی جدولهایم.» منبع (Resource) مفهوم مهم برای کلاینت است، نه ردیف جدول. به تعبیر Fielding: "Any information that can be named can be a resource". مسیر
POST /v1/orders/{id}/cancellationبا REST سازگار است؛ اماPATCHکه هر مقداری را برایstatusبپذیرد، جدول داخلی را به قرارداد نشت داده است. - «اعتبارسنجی (Validation) کار Framework است.» در Go این کار پنهان نمیشود: Decode، بررسی شکل درخواست و قواعد کسبوکار سه مرحله با سه کد 400، 422 و 409 هستند. هرکدام را صریح مینویسید.
- «Swagger مستندات میسازد، پس مستندات درست است.» Annotation و کد بدون بررسی از هم فاصله میگیرند. یا از Spec کد بسازید، یا از کد Spec، یا مثل این فصل مسیرها را در برابر Spec تست کنید.
از کجا آمده (History)
Roy Fielding در رسالهٔ سال ۲۰۰۰ خود در UC Irvine با عنوان «Architectural Styles and the Design of Network-based Software Architectures» نام REST را مطرح کرد. فصل پنجم رابط یکنواخت (Uniform interface) را با چهار قید تعریف میکند: "identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state". منبع هم "a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time" است. اغلب JSON APIهایی که امروز REST نامیده میشوند سه قید اول را رعایت میکنند و Link را محدود به صفحهٔ بعد یا Location پس از ساخت به کار میبرند.
قطعههای HTTP بهتدریج آمدهاند: PATCH در RFC 5789، مارس ۲۰۱۰؛ JSON Merge Patch در RFC 7396، اکتبر ۲۰۱۴؛ Headerهای Link در RFC 5988 و جانشینش RFC 8288، اکتبر ۲۰۱۷. RFC 6585 در آوریل ۲۰۱۲ کدهای 428 Precondition Required و 429 Too Many Requests را افزود. RFC 7807 در مارس ۲۰۱۶ قالب Problem Details را تعریف کرد. RFC 9457 در ژوئیهٔ ۲۰۲۳ میگوید "obsoletes RFC 7807" و Registry نوع خطا و راهنمای چند خطا را اضافه میکند. RFC 9110 در ژوئن ۲۰۲۲ معنای HTTP را یکپارچه و نام 422 را به "Unprocessable Content" تبدیل کرد؛ http.StatusText(422) در Go هنوز "Unprocessable Entity" است. Header Idempotency-Key که Stripe سالها استفاده کرده، در draft-ietf-httpapi-idempotency-key-header استاندارد میشود؛ نسخهٔ 09 ذکرشده در مبنای این فصل هنوز Internet-Draft است.
قرارداد از Swagger Specification شروع شد: 1.0 در ۱۰ اوت ۲۰۱۱ و 2.0 در ۸ سپتامبر ۲۰۱۴. Swagger 2.0 در ۳۱ دسامبر ۲۰۱۵ به OpenAPI Initiative واگذار شد و با نام OpenAPI Specification ادامه یافت. OpenAPI 3.1.0، منتشرشده در ۱۵ فوریهٔ ۲۰۲۱، نخستین نسخهای است که Schema Object آن "is a superset of JSON Schema Specification Draft 2020-12" و webhooks دارد. 3.1.1 انتشار اصلاحی است؛ شاخهٔ جدید 3.2.x و نسخهٔ آن 3.2.1 است. در Go، swaggo/swag از Commentها Swagger 2.0 میسازد و oapi-codegen و ogen از OpenAPI 3 کد Go تولید میکنند.
Go 1.22 در ۶ فوریهٔ ۲۰۲۴ Method و Wildcard را به الگوی ServeMux افزود: "Wildcards in patterns, like /items/{id}, match segments of the URL path. The actual segment value may be accessed by calling the Request.PathValue method". این تغییر دلیل اصلی انتخاب Router ثالث برای JSON API را کنار زد. Go 1.23، Request.Pattern و Range-over-func؛ Go 1.24، omitzero، t.Context() و slog.DiscardHandler را آورد. Go 1.27 بستهٔ encoding/json/v2 را عادی کرد و encoding/json را روی آن بازنوشت: "the exact text of error messages may differ". پست فوریهٔ ۲۰۲۴ Mat Ryer با عنوان «How I write HTTP services in Go after 13 years» الگوی این فصل را شرح میدهد: NewServer، routes.go، main که فقط run را صدا میزند، Maker function، encode/decode جنریک و تست End-to-end با فراخوانی run.
Go
قبل (Before)
پیشنویس اول یک Handler دارد که روی Method شاخه میزند، Map سراسری دارد و خطا را 200 میفرستد. بدنهٔ نامحدود مستقیم وارد Struct ذخیرهشده میشود؛ فیلد ناشناخته و خطای Decode نادیده میمانند. صفحهها شماره و Total دارند و PUT هرچه هست بازنویسی میکند. هر تست یک نمونه از گمراه شدن کلاینت را ثبت میکند.
// Package before is a first-draft products API that works in a demo: global
// state, one function per verb, errors as 200 + {"error": "..."}, offset
// pagination with a COUNT, blind updates and validation mixed into handlers.
package before
import (
"encoding/json"
"net/http"
"sort"
"strconv"
"sync"
)
type Product struct {
ID int `json:"id"`
SKU string `json:"sku"`
Name string `json:"name"`
Price int `json:"price"`
}
var (
mu sync.Mutex
db = map[int]*Product{} // global: every test shares it
nextID = 1
)
// Reset exists only because the state is global.
func Reset() {
mu.Lock()
defer mu.Unlock()
db, nextID = map[int]*Product{}, 1
}
func Routes(mux *http.ServeMux) {
mux.HandleFunc("/products", products) // one handler switches on the method
}
func products(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
size, _ := strconv.Atoi(r.URL.Query().Get("size")) // no maximum
if size == 0 {
size = 10
}
mu.Lock()
all := make([]*Product, 0, len(db))
for _, p := range db {
all = append(all, p)
}
mu.Unlock()
sort.Slice(all, func(i, j int) bool { return all[i].ID > all[j].ID })
from := page * size
if from > len(all) {
from = len(all)
}
to := min(from+size, len(all))
json.NewEncoder(w).Encode(map[string]any{"items": all[from:to], "total": len(all)})
case http.MethodPost:
var p Product
json.NewDecoder(r.Body).Decode(&p) // unbounded body, unknown fields ignored, error dropped
if p.SKU == "" {
json.NewEncoder(w).Encode(map[string]string{"error": "sku required"}) // 200 OK
return
}
mu.Lock()
p.ID = nextID
nextID++
db[p.ID] = &p
mu.Unlock()
json.NewEncoder(w).Encode(p) // 200, no Location
case http.MethodPut:
var p Product
json.NewDecoder(r.Body).Decode(&p)
mu.Lock()
db[p.ID] = &p // last write wins, creates the row if it did not exist
mu.Unlock()
json.NewEncoder(w).Encode(p)
default:
w.Write([]byte("unsupported"))
}
}package before
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func call(t *testing.T, method, target, body string) *httptest.ResponseRecorder {
t.Helper()
mux := http.NewServeMux()
Routes(mux)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body)))
return rec
}
// The draft "works", but its failure modes are invisible to HTTP clients.
func TestTheDraftHidesFailures(t *testing.T) {
Reset()
if rec := call(t, "POST", "/products", `{"name":"no sku"}`); rec.Code != 200 {
t.Fatalf("validation failure reported as %d", rec.Code)
}
if rec := call(t, "POST", "/products", `{"sku":"A","colour":"red","price":"9"}`); rec.Code != 200 {
t.Fatalf("bad body reported as %d", rec.Code)
}
if rec := call(t, "DELETE", "/products", ""); rec.Code != 200 {
t.Fatalf("unsupported method reported as %d", rec.Code)
}
}
// Two clients edit the same product; the second silently erases the first.
func TestLostUpdate(t *testing.T) {
Reset()
call(t, "POST", "/products", `{"sku":"MUG","name":"Mug","price":900}`)
call(t, "PUT", "/products", `{"id":1,"sku":"MUG","name":"Mug","price":1200}`) // client A: new price
call(t, "PUT", "/products", `{"id":1,"sku":"MUG","name":"Coffee mug","price":900}`) // client B: new name, stale price
var page struct{ Items []Product }
_ = json.NewDecoder(call(t, "GET", "/products", "").Body).Decode(&page)
if page.Items[0].Price != 900 {
t.Fatalf("expected A's price change to be lost, got %+v", page.Items[0])
}
}
// Offset paging skips or repeats rows when the list changes between pages.
func TestOffsetPagingRepeatsRows(t *testing.T) {
Reset()
for range 4 {
call(t, "POST", "/products", `{"sku":"X"}`)
}
var p1, p2 struct{ Items []Product }
_ = json.NewDecoder(call(t, "GET", "/products?page=0&size=2", "").Body).Decode(&p1) // ids 4 3
call(t, "POST", "/products", `{"sku":"NEW"}`) // id 5 at the head
_ = json.NewDecoder(call(t, "GET", "/products?page=1&size=2", "").Body).Decode(&p2) // ids 3 2
if p1.Items[1].ID != p2.Items[0].ID {
t.Fatalf("expected id %d twice, pages %v / %v", p1.Items[1].ID, p1.Items, p2.Items)
}
}بعد (After)
سرویس کامل به بستههای جدا تقسیم شده که هرکدام در بخش مفهوم خودش میآید. اینجا دو سر آن را میبینید. NewServer کل API را به شکل یک http.Handler میسازد: ابتدا جدول مسیرها (Routes table)، سپس Middleware مشترک همهٔ مسیرها.
// Package httpapi is the HTTP adapter: routes, handlers, DTO decoding,
// Problem Details, ETags, pagination links and the middleware stack. It
// depends on the service layer, never the other way round.
package httpapi
import (
"context"
"log/slog"
"net/http"
"time"
"academy/rest-api-project/idempotency"
"academy/rest-api-project/openapi"
"academy/rest-api-project/pagination"
"academy/rest-api-project/service"
)
// Limiter is the rate limiting hook: nil means no limit. Plug in a token
// bucket (golang.org/x/time/rate) keyed by API key or client IP.
type Limiter interface {
Allow(r *http.Request) (ok bool, retryAfter time.Duration)
}
// Deps lists every dependency of the HTTP layer. Mat Ryer's NewServer takes
// them as plain arguments; a struct is the same idea once the list grows.
type Deps struct {
Logger *slog.Logger
Products *service.Service
Cursors pagination.Codec
Idempotency *idempotency.Store
RequireIdemKey bool
Limiter Limiter
Ready func(context.Context) error
MaxBodyBytes int64
}
// NewServer builds the whole API as one http.Handler: the mux with every
// route, then the middleware that applies to all of them, outermost last.
func NewServer(d Deps) http.Handler {
mux := http.NewServeMux()
for _, rt := range routes(d) {
mux.Handle(rt.pattern, rt.handler)
}
var h http.Handler = problemFallback(mux)
h = rateLimit(d.Limiter, h)
h = logRequests(d.Logger, h)
h = recoverPanics(d.Logger, h)
h = requestID(h)
return h
}
type route struct {
pattern string
handler http.Handler
documented bool // part of the public contract in openapi.json
}
// routes is the entire API surface in one table: read it to know the API.
func routes(d Deps) []route {
idem := d.Idempotency.Middleware(d.RequireIdemKey, d.MaxBodyBytes)
return []route{
{"GET /v1/products", handleList(d.Products, d.Cursors), true},
{"POST /v1/products", idem(handleCreate(d.Products, d.MaxBodyBytes)), true},
{"GET /v1/products/{id}", handleGet(d.Products), true},
{"PUT /v1/products/{id}", handleReplace(d.Products, d.MaxBodyBytes), true},
{"PATCH /v1/products/{id}", handlePatch(d.Products, d.MaxBodyBytes), true},
{"DELETE /v1/products/{id}", handleDelete(d.Products), true},
{"GET /healthz", handleHealthz(), false},
{"GET /readyz", handleReadyz(d.Ready), false},
{"GET /openapi.json", openapi.SpecHandler(), false},
{"GET /docs", openapi.DocsHandler("/openapi.json"), false},
}
}
// Routes returns the documented "METHOD /path" patterns, for the contract test.
func Routes() []string {
var out []string
for _, rt := range routes(Deps{Idempotency: idempotency.NewStore(0, time.Now)}) {
if rt.documented {
out = append(out, rt.pattern)
}
}
return out
}Run خود برنامه به شکل تابع است؛ هم main و هم تست End-to-end آن را صدا میزنند.
// Package app holds Run, the whole program as a function: main only calls
// it, tests call it too (Mat Ryer's run function pattern).
package app
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
"academy/rest-api-project/config"
"academy/rest-api-project/httpapi"
"academy/rest-api-project/idempotency"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/pagination"
"academy/rest-api-project/service"
)
// Run takes the operating system as arguments and returns an error instead
// of calling os.Exit, so a test can start the real program in a goroutine.
func Run(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()
cfg, err := config.Load(getenv)
if err != nil {
return fmt.Errorf("config: %w", err)
}
fs := flag.NewFlagSet(args[0], flag.ContinueOnError)
fs.StringVar(&cfg.Addr, "addr", cfg.Addr, "listen address (overrides API_ADDR)")
if err := fs.Parse(args[1:]); err != nil {
return err
}
log := slog.New(slog.NewJSONHandler(stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
// Composition root: the only place that knows every concrete type.
// Both repositories satisfy this type, so swapping in pgrepo.New(db) (with a
// *sql.DB opened through a registered driver) is a one-line change.
var repo interface {
service.Repository
Ping(context.Context) error
} = memrepo.New()
svc := service.New(repo, time.Now, newID)
var draining atomic.Bool
handler := httpapi.NewServer(httpapi.Deps{
Logger: log,
Products: svc,
Cursors: pagination.Codec{Key: cfg.CursorKey},
Idempotency: idempotency.NewStore(24*time.Hour, time.Now),
RequireIdemKey: cfg.RequireIdemKey,
MaxBodyBytes: cfg.MaxBodyBytes,
Ready: func(ctx context.Context) error {
if draining.Load() {
return errors.New("shutting down")
}
return repo.Ping(ctx)
},
})
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return err
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
ErrorLog: slog.NewLogLogger(log.Handler(), slog.LevelWarn),
}
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(ln) }()
log.Info("listening", "addr", ln.Addr().String())
select {
case err := <-serveErr:
return err
case <-ctx.Done():
}
// Graceful shutdown: fail readiness first and give the load balancer
// DrainDelay to notice, then stop accepting and wait for in-flight
// requests, bounded by the shutdown timeout.
draining.Store(true)
log.Info("shutting down", "drain_delay", cfg.DrainDelay.String(), "timeout", cfg.ShutdownTimeout.String())
time.Sleep(cfg.DrainDelay)
sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), cfg.ShutdownTimeout)
defer scancel()
if err := srv.Shutdown(sctx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
return err
}
log.Info("stopped")
return nil
}
func newID() string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return "prd_" + hex.EncodeToString(b)
}// Command api runs the products API. All the work is in app.Run.
package main
import (
"context"
"fmt"
"os"
"academy/rest-api-project/app"
)
func main() {
if err := app.Run(context.Background(), os.Args, os.Getenv, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}زاویهٔ Go
کتابخانهٔ استاندارد Go سرور HTTP، Router، JSON codec، Logger ساختیافته و Test server آمادهٔ کار واقعی دارد، اما قراردادهای Framework را تحمیل نمیکند. برای همین API یا شبیه فایل «قبل» میشود یا نسخهای کوچک و صریح از کارهایی که Laravel و Spring انجام میدهند. DTO، نگاشت خطا و اتصال وابستگیها (Wiring) را خودتان مینویسید؛ در عوض رفتار قابل خواندن و تست کردن است. اکوسیستم شکاف مشخص را پر میکند: go-playground/validator برای Tag validation و Validator پیشفرض Gin، oapi-codegen و ogen برای Spec-first، swaggo/swag برای Swagger مبتنی بر Comment، pgx برای PostgreSQL و golang.org/x/time/rate برای محدودسازی. آموزش «Developing a RESTful API with Go and Gin» در go.dev نقطهٔ مقایسهٔ خوبی است: /albums را از Slice حافظه با Gin سرو میکند و خودش میگوید "storing data in memory means that the set of albums will be lost each" بار که سرور متوقف شود. آن آموزش جداسازی DTO، Error envelope، Pagination یا تست ندارد، چون دربارهٔ Endpoint اول است. Gin، Echo، Chi و huma انتخابهای معتبریاند؛ الگوهای این صفحه روی همه قابل استفادهاند، چون در پایان همگی http.Handler هستند.
فهرست مفاهیم (Concept catalogue)
برنامهریزی پروژه، مدلسازی منبع و طراحی URL حیاتی
به زبان ساده: پیش از Handler بنویسید کلاینت چه میبیند: منبعها (Resources)، مجموعهها، URLها، فیلدهای قابل نوشتن و فقطخواندنی و کدهای وضعیت هر عملیات. این برنامهریزی پروژه (Project planning) مبنای کد، سند OpenAPI و تست است.
بدفهمی رایج: «مدلسازی منبع (Resource modelling) یعنی یک Endpoint برای هر جدول.» Resource مفهوم کلاینت است. جدول products با ستون archived_at میتواند یک Resource باشد؛ سفارش و ردیفهایش یک تجمیع (Aggregate) با یک URL برای سفارشاند. تغییر وضعیت همراه Refund و Notification بهتر است منبع خودش را داشته باشد: POST /v1/orders/{id}/cancellation، نه PATCH یک ستون Status. AIP-122 هم نام منبع را مسیر شناسهٔ مجموعه و منبع میبیند؛ مثل publishers/123/books/les-miserables.
تعریف: Project planning برای HTTP API چهار خروجی دارد: مدل Resource شامل اسمها، فیلدها، بخشهای فقطخواندنی و چرخهٔ عمر؛ طراحی URL (URL design) با نام جمع، ID پایدار و مبهم، تودرتویی فقط برای مالکیت واقعی و پیشوند نسخهٔ اصلی؛ جدول عملیات شامل Method، Path، DTO درخواست و پاسخ، Status code، Header و Idempotency؛ و قواعد غیرعملکردی مانند سقف صفحه و بدنه، Timeout، Rate limit و Auth. در این فصل جدول سطح API در یک دقیقه و openapi.json همین برنامهاند.
1 Nouns product (sku, name, price_cents, currency, status, tags)
2 Read-only id, version, created_at, updated_at
3 Lifecycle draft -> active -> archived (archived is frozen)
4 URLs /v1/products collection
/v1/products/{id} item (id is opaque: prd_9b6b2a44e8ef67ef)
5 Operations GET list · POST create · GET · PUT · PATCH · DELETE
6 Rules limit <= 100, body <= 1 MiB, If-Match on writes, Idempotency-Key on POST
7 Contract openapi.json written from 1-6, then code, then tests against bothسناریوی واقعی: در سرویس کاتالوگ، بازاریابی GET /products?category=shoes میخواهد و انبار GET /products/{sku}. در رزرو، Confirm و Cancel عملیات دارای قاعدهاند. SaaS چندمستاجری Tenant را در Token میگذارد تا از مسیر جعل نشود. API عمومی ID غیرقابل حدس میخواهد، نه عدد ترتیبی.
| قاعدهٔ طراحی نشانی (URL design) | خوب | پرهیز کنید | چرا |
|---|---|---|---|
| اسم جمع برای مجموعه | /v1/products | /v1/getProducts، /v1/product | Method خودش فعل است |
| شناسهٔ پایدار و مبهم (Opaque ID) | prd_9b6b2a44e8ef67ef | /products/17 | قابل شمارش نیست و با جابهجایی DB عوض نمیشود |
| تودرتویی فقط برای مالکیت | /v1/orders/{id}/lines | /v1/customers/{c}/orders/{o}/lines/{l}/notes | مسیر عمیق کلید را تکرار و تغییر را سخت میکند |
| عمل به شکل زیرمنبع (Sub-resource) | POST /v1/orders/{id}/cancellation | PATCH {"status":"cancelled"} با اثر جانبی | قاعده و Audit یک جا میمانند |
| Query string برای نما | ?status=active&sort=-price | /v1/products/active/by-price | Filterها ترکیب میشوند، مسیرها نه |
| نسخهٔ اصلی در مسیر | /v1/... | /v1.3/... | AIP-185: "Google APIs use v1, not v1.0, v1.1, or v1.4.2" |
| یک انتخاب برای snake_case یا camelCase | همهجا price_cents | ترکیب هر دو | Generated client نامها را 1:1 نگاشت میکند |
راهحل / نحوهٔ استفاده: ابتدا جدول عملیات و OpenAPI را بنویسید؛ Contract test مسیرها و سند را هماهنگ نگه میدارد. قواعد مستقل از زبان در REST API Design است.
رسیدگیکنندهها، Maker function و جدول مسیرها حیاتی
به زبان ساده: رسیدگیکننده (Handler) یک درخواست HTTP را به یک پاسخ تبدیل میکند: Path و Body را میخواند، Service را صدا میزند و پاسخ مینویسد. تابع سازندهٔ Handler یا Maker function وابستگیها را میگیرد، مثل handleCreate(svc, maxBytes). ثبت همهٔ مسیرها در یک جدول باعث میشود با خواندن یک تابع کل API را ببینید.
بدفهمی رایج: «Handler باید متد یک Server struct بزرگ باشد.» توصیهٔ قدیمی Mat Ryer هم همین بود، اما تغییرش داد: "My handlers used to be methods hanging off a server struct, but I no longer do this." متد به همهٔ فیلدها دسترسی دارد؛ وابستگی واقعی پنهان میشود و تست باید کل Struct را بسازد. پارامترهای Maker function فهرست وابستگی آناند.
تعریف: Maker function یک http.Handler برمیگرداند؛ به قول Ryer: "My handler functions don’t implement http.Handler or http.HandlerFunc directly, they return them". Closure میتواند Setup مخصوص همان Handler را نگه دارد. مسیرها از الگوی Go 1.22 یعنی "METHOD /path/{wildcard}" و r.PathValue("id") استفاده میکنند. اگر مسیر وجود داشته باشد ولی Method فرق کند، خود ServeMux با 405 و Allow جواب میدهد. تابع routes(d Deps) []route معادل routes.go در نوشتهٔ Ryer است: "entire API surface" در یک جا.
1 NewServer(deps)
2 for each route in routes(deps): mux.Handle("POST /v1/products", idem(handleCreate(svc, max)))
3 wrap: problemFallback(mux) -> rateLimit -> logRequests -> recoverPanics -> requestID
4 request POST /v1/products
5 requestID -> recover -> log -> rateLimit -> mux finds pattern -> idempotency -> handleCreate
6 handleCreate: decode[ProductWrite] -> svc.Create -> encode 201سناریوی واقعی: توسعهدهنده برای فهمیدن مسیرهای نیازمند Auth یک جدول میخواند؛ تست فقط Fakeهایی را میفرستد که Maker میگیرد؛ افزودن GET /v1/products/{id}/history یک سطر و یک Maker میخواهد؛ دیدن *sql.DB در امضای Handler به بازبین خبر میدهد که لایهبندی دور زده شده است.
| سبک | وابستگی پیدا است؟ | تست مستقل | کاربرد |
|---|---|---|---|
Maker function با خروجی http.Handler | بله، پارامترها | بله | این فصل و Mat Ryer |
| متد روی Server struct | نه؛ هر فیلدی ممکن است | کل Struct لازم است | سبک قدیمی و بسیاری از آموزشها |
متد تولیدشدهٔ ServerInterface در oapi-codegen | باز هم فیلدهای Struct | بله، با Struct جعلی | پروژهٔ Spec-first |
Handler فریمورک مثل func(c *gin.Context) | از Closure یا Struct | با Test kit همان Framework | Gin، Echo |
راهحل / نحوهٔ استفاده: فایل زیر کل رفتار HTTP منبع Products است. هر تابع مسیر خطی Parse، Call، نگاشت خطا در writeError و Encode را طی میکند.
package httpapi
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"academy/rest-api-project/dto"
"academy/rest-api-project/mergepatch"
"academy/rest-api-project/pagination"
"academy/rest-api-project/problem"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
// Maker functions return the handler; dependencies are their arguments.
func handleCreate(svc *service.Service, maxBytes int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
in, prob := decode[dto.ProductWrite](w, r, maxBytes, "application/json")
if prob != nil {
problem.Write(w, r, prob)
return
}
p, err := svc.Create(r.Context(), in.Draft())
if err != nil {
writeError(w, r, err)
return
}
w.Header().Set("Location", "/v1/products/"+p.ID)
w.Header().Set("ETag", etag(p.Version))
encode(w, http.StatusCreated, dto.View(p))
})
}
func handleGet(svc *service.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, err := svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
writeError(w, r, err)
return
}
tag := etag(p.Version)
w.Header().Set("ETag", tag)
if inm := r.Header.Get("If-None-Match"); inm != "" && parseCondition(inm).weakMatch(tag) {
w.WriteHeader(http.StatusNotModified)
return
}
encode(w, http.StatusOK, dto.View(p))
})
}
// handleReplace is PUT: the body is the complete new representation.
func handleReplace(svc *service.Service, maxBytes int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cond, prob := requireIfMatch(r)
if prob != nil {
problem.Write(w, r, prob)
return
}
in, prob := decode[dto.ProductWrite](w, r, maxBytes, "application/json")
if prob != nil {
problem.Write(w, r, prob)
return
}
cur, err := svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
writeError(w, r, err)
return
}
if !cond.strongMatch(etag(cur.Version)) {
problem.Write(w, r, staleProblem())
return
}
saveAndRespond(w, r, svc, cur.Version, in)
})
}
// handlePatch is RFC 7396 JSON Merge Patch: apply the patch to the current
// writable representation, then decode and validate the result like a PUT.
func handlePatch(svc *service.Service, maxBytes int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cond, prob := requireIfMatch(r)
if prob != nil {
problem.Write(w, r, prob)
return
}
if prob := requireMediaType(r, mergepatch.MediaType); prob != nil {
problem.Write(w, r, prob)
return
}
patch, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBytes))
if err != nil {
problem.Write(w, r, decodeProblem(err))
return
}
cur, err := svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
writeError(w, r, err)
return
}
if !cond.strongMatch(etag(cur.Version)) {
problem.Write(w, r, staleProblem())
return
}
doc, _ := json.Marshal(dto.WriteOf(cur))
merged, err := mergepatch.ApplyJSON(doc, patch)
if err != nil {
problem.Write(w, r, problem.New(http.StatusBadRequest, "malformed-body", "Malformed merge patch", err.Error()))
return
}
// Re-run the normal decoder on the merged document: unknown or
// read-only members ("id", "version") are rejected here.
r2 := r.Clone(r.Context())
r2.Header.Set("Content-Type", "application/json")
r2.Body = io.NopCloser(strings.NewReader(string(merged)))
in, prob := decode[dto.ProductWrite](w, r2, maxBytes, "application/json")
if prob != nil {
problem.Write(w, r, prob)
return
}
saveAndRespond(w, r, svc, cur.Version, in)
})
}
// saveAndRespond writes with the version the precondition matched; the
// repository re-checks it atomically, so a concurrent writer still gets 412.
func saveAndRespond(w http.ResponseWriter, r *http.Request, svc *service.Service, version int64, in dto.ProductWrite) {
p, err := svc.Replace(r.Context(), r.PathValue("id"), version, in.Draft())
if err != nil {
writeError(w, r, err)
return
}
w.Header().Set("ETag", etag(p.Version))
encode(w, http.StatusOK, dto.View(p))
}
func handleDelete(svc *service.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cond, prob := requireIfMatch(r)
if prob != nil {
problem.Write(w, r, prob)
return
}
id := r.PathValue("id")
cur, err := svc.Get(r.Context(), id)
if err != nil {
writeError(w, r, err)
return
}
if !cond.strongMatch(etag(cur.Version)) {
problem.Write(w, r, staleProblem())
return
}
if err := svc.Delete(r.Context(), id, cur.Version); err != nil {
writeError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
})
}
// handleList: filtering (status, min_price, max_price), sorting (sort=-price)
// and keyset pagination (limit, cursor) with a Link: rel="next" header.
func handleList(svc *service.Service, cursors pagination.Codec) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q, fingerprint, prob := parseList(r.URL.Query(), cursors)
if prob != nil {
problem.Write(w, r, prob)
return
}
page, err := svc.List(r.Context(), q)
if err != nil {
writeError(w, r, err)
return
}
out := dto.ListView{Data: make([]dto.ProductView, 0, len(page.Items))}
for _, p := range page.Items {
out.Data = append(out.Data, dto.View(p))
}
if page.Next != nil {
out.NextCursor = cursors.Encode(fingerprint, *page.Next)
out.HasMore = true
next := *r.URL
v := next.Query()
v.Set("cursor", out.NextCursor)
next.RawQuery = v.Encode()
w.Header().Set("Link", "<"+next.RequestURI()+`>; rel="next"`)
}
encode(w, http.StatusOK, out)
})
}
func parseList(v url.Values, cursors pagination.Codec) (product.ListQuery, string, *problem.Problem) {
bad := func(param, detail string) *problem.Problem {
return problem.New(http.StatusBadRequest, "invalid-query", "Invalid query parameter", param+": "+detail)
}
var q product.ListQuery
n := 0
if s := v.Get("limit"); s != "" {
var err error
if n, err = strconv.Atoi(s); err != nil {
return q, "", bad("limit", "must be an integer")
}
}
limit, ok := pagination.ClampLimit(n)
if !ok {
return q, "", bad("limit", "must not be negative")
}
q.Limit = limit
if s := v.Get("status"); s != "" {
if !product.Status(s).Valid() {
return q, "", bad("status", "must be draft, active or archived")
}
q.Status = product.Status(s)
}
for _, f := range []struct {
name string
dst **int64
}{{"min_price", &q.MinPrice}, {"max_price", &q.MaxPrice}} {
if s := v.Get(f.name); s != "" {
n, err := strconv.ParseInt(s, 10, 64)
if err != nil || n < 0 {
return q, "", bad(f.name, "must be a non-negative integer (cents)")
}
*f.dst = &n
}
}
sort := v.Get("sort")
if sort == "" {
sort = "-created_at"
}
field, desc := strings.CutPrefix(sort, "-")
switch product.SortField(field) {
case product.SortCreatedAt, product.SortPrice, product.SortName:
q.Sort, q.Desc = product.SortField(field), desc
default:
return q, "", bad("sort", "must be one of created_at, price, name, optionally prefixed with -")
}
// The cursor is only valid for the same filter and sort it was made for.
fp := url.Values{"status": {v.Get("status")}, "min_price": {v.Get("min_price")},
"max_price": {v.Get("max_price")}, "sort": {sort}}.Encode()
if s := v.Get("cursor"); s != "" {
c, err := cursors.Decode(fp, s)
if err != nil {
return q, "", bad("cursor", "invalid or does not match the current filter and sort")
}
q.After = &c
}
return q, fp, nil
}
func handleHealthz() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
encode(w, http.StatusOK, map[string]string{"status": "ok"})
})
}
// handleReadyz answers 503 while a dependency is down or the server is
// draining, so the load balancer stops sending traffic before shutdown.
func handleReadyz(ready func(context.Context) error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ready != nil {
if err := ready(r.Context()); err != nil {
problem.Write(w, r, problem.New(http.StatusServiceUnavailable, "", "", err.Error()))
return
}
}
encode(w, http.StatusOK, map[string]string{"status": "ready"})
})
}
// writeError is the one place where domain errors become status codes.
func writeError(w http.ResponseWriter, r *http.Request, err error) {
var p *problem.Problem
switch {
case errors.Is(err, product.ErrNotFound):
p = problem.New(http.StatusNotFound, "", "", "no product with id "+r.PathValue("id"))
case errors.Is(err, product.ErrSKUTaken):
p = problem.New(http.StatusConflict, "sku-taken", "SKU already exists", "")
case errors.Is(err, product.ErrVersionMismatch):
p = staleProblem() // lost the race inside the repository's version check
case errors.Is(err, product.ErrInvalidTransition):
p = problem.New(http.StatusConflict, "invalid-transition", "Status change not allowed", err.Error())
default:
// The access-log middleware records the cause; the client gets no internals.
if rec, ok := w.(interface{ SetError(error) }); ok {
rec.SetError(err)
}
p = problem.New(http.StatusInternalServerError, "", "", "")
}
problem.Write(w, r, p)
}نوعهای درخواست و پاسخ (DTOs) حیاتی
به زبان ساده: شیء انتقال داده (Data transfer object یا DTO) فقط برای قالب JSON روی شبکه وجود دارد. ProductWrite چیزی است که کلاینت حق ارسالش را دارد؛ ProductView چیزی است که دریافت میکند. نوع Domain یعنی product.Product مستقیم از JSON خوانده یا به JSON نوشته نمیشود.
بدفهمی رایج: «یک Struct با JSON tag برای همهچیز، کد را کم میکند.» آن وقت کلاینت میتواند id یا version بنویسد، فیلد داخلی تازه همان روز وارد پاسخ عمومی میشود، تغییر نام فیلد Go قرارداد را میشکند و ساخت و خواندن شکل متفاوتی ندارند. Ryer دربارهٔ نوع مخصوص Handler میگوید جلوی "other handlers from relying on data you may not consider stable" را میگیرد.
تعریف: Write DTO فقط فیلدهای قابل نوشتن، نام JSON، قواعد Validation و تبدیل به ورودی Domain با Draft() را دارد. View DTO با View(p) از Domain ساخته میشود؛ تبدیل Slice از nil به [] و پنهان کردن فیلد برای مخاطب خاص هم همینجاست. گزینهٔ omitzero در Go 1.24 مقدارهای صفری مثل time.Time صفر را حذف میکند که omitempty از پسشان برنمیآید؛ یادداشت انتشار آن را "clearer and less error-prone than omitempty" مینامد.
wire HTTP adapter domain
1 {"sku":"MUG-1",...} ──────▶ dto.ProductWrite ── Draft() ──▶ product.Draft
2 service.Create -> product.Product
3 {"id":"prd_..",...} ◀────── dto.ProductView ◀── View(p) ── product.Product
4 {"id":"x"} in a POST ─────▶ unknown field "id": 400 (DisallowUnknownFields)سناریوی واقعی: کلاینت با انتساب انبوه (Mass assignment)، is_admin را true میکند؛ Refactor نام فیلد برنامهٔ موبایل را میشکند؛ یک شریک price را رشته و دیگری عدد میخواهد؛ password_hash ناخواسته وارد پاسخ فهرست میشود.
| دغدغه | بدون DTO | با DTO |
|---|---|---|
| انتساب انبوه (Mass assignment) | هر فیلد JSON به Model میرسد | فقط فیلدهای ProductWrite وجود دارند |
| افشای جزئیات داخلی | فیلد تازه عمومی میشود | View همهٔ فیلدهای عمومی را مشخص میکند |
| شکل متفاوت هر عملیات | ممکن نیست | یک Type برای هر عملیات |
| Refactor نام Go | کلاینت میشکند | فقط JSON tag قرارداد است |
| هزینه | Type کمتر | تابع Mapping برای نوشتن و تست |
راهحل / نحوهٔ استفاده: DTO را در بستهٔ dto نگه دارید؛ اگر فقط یک Handler مصرفش میکند، مثل type request struct در الگوی Ryer همانجا تعریفش کنید. جزئیات Struct tag در JSON, XML & Encoding است.
// Package dto holds the wire types of the API: what clients send and what
// they get back. They are not the domain type, so the JSON contract can stay
// stable while product.Product evolves.
package dto
import (
"context"
"fmt"
"time"
"unicode/utf8"
"academy/rest-api-project/product"
"academy/rest-api-project/validation"
)
// ProductWrite is the body of POST, PUT and (after merge) PATCH. It carries
// both validation styles: the validate tags for go-playground/validator and
// a hand-written Valid method. The API uses Valid; the test proves they agree.
type ProductWrite struct {
SKU string `json:"sku" validate:"required,min=3,max=32"`
Name string `json:"name" validate:"required,max=200"`
PriceCents *int64 `json:"price_cents" validate:"required,gte=0,lte=100000000"` // pointer: absent or null is not 0
Currency string `json:"currency" validate:"len=3,uppercase"`
Status string `json:"status" validate:"oneof=draft active archived"`
Tags []string `json:"tags,omitempty" validate:"max=10,dive,min=1,max=30"`
}
// Valid is the hand-written validator: plain Go, no reflection, every rule
// visible and debuggable; it may use ctx for lookups (feature flags, tenant).
func (w ProductWrite) Valid(_ context.Context) []validation.Violation {
var v []validation.Violation
add := func(ptr, msg string) { v = append(v, validation.Violation{Pointer: ptr, Detail: msg}) }
switch n := utf8.RuneCountInString(w.SKU); { // characters, as the validator tags count
case n == 0:
add("/sku", "is required")
case n < 3:
add("/sku", "must be at least 3")
case n > 32:
add("/sku", "must be at most 32")
}
if w.Name == "" {
add("/name", "is required")
} else if utf8.RuneCountInString(w.Name) > 200 {
add("/name", "must be at most 200")
}
switch {
case w.PriceCents == nil:
add("/price_cents", "is required")
case *w.PriceCents < 0:
add("/price_cents", "must be at least 0")
case *w.PriceCents > 100_000_000:
add("/price_cents", "must be at most 100000000")
}
if utf8.RuneCountInString(w.Currency) != 3 {
add("/currency", "must have length 3")
} else if !isUpper(w.Currency) {
add("/currency", "must be upper case")
}
if !product.Status(w.Status).Valid() {
add("/status", "must be one of: draft active archived")
}
if len(w.Tags) > 10 {
add("/tags", "must be at most 10")
}
for i, t := range w.Tags {
if n := utf8.RuneCountInString(t); n < 1 {
add(fmt.Sprintf("/tags/%d", i), "must be at least 1")
} else if n > 30 {
add(fmt.Sprintf("/tags/%d", i), "must be at most 30")
}
}
return v
}
func isUpper(s string) bool {
for _, r := range s {
if r < 'A' || r > 'Z' {
return false
}
}
return true
}
// Cents is a helper for building a ProductWrite in Go code.
func Cents(n int64) *int64 { return &n }
// Draft converts the validated body to the domain input (Valid has checked
// that PriceCents is set).
func (w ProductWrite) Draft() product.Draft {
return product.Draft{SKU: w.SKU, Name: w.Name, PriceCents: *w.PriceCents, Currency: w.Currency, Status: product.Status(w.Status), Tags: w.Tags}
}
// WriteOf is the inverse, used by PATCH to build the document the merge
// patch is applied to.
func WriteOf(p product.Product) ProductWrite {
return ProductWrite{SKU: p.SKU, Name: p.Name, PriceCents: Cents(p.PriceCents), Currency: p.Currency, Status: string(p.Status), Tags: p.Tags}
}
// ProductView is the response representation, the Go counterpart of a
// Laravel API Resource's toArray.
type ProductView struct {
ID string `json:"id"`
SKU string `json:"sku"`
Name string `json:"name"`
PriceCents int64 `json:"price_cents"`
Currency string `json:"currency"`
Status string `json:"status"`
Tags []string `json:"tags"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// View maps the aggregate to its representation.
func View(p product.Product) ProductView {
tags := p.Tags
if tags == nil {
tags = []string{} // "tags": [] rather than null
}
return ProductView{ID: p.ID, SKU: p.SKU, Name: p.Name, PriceCents: p.PriceCents, Currency: p.Currency,
Status: string(p.Status), Tags: tags, Version: p.Version, CreatedAt: p.CreatedAt, UpdatedAt: p.UpdatedAt}
}
// ListView is the collection envelope: data plus the cursor for the next
// page (also sent as a Link header).
type ListView struct {
Data []ProductView `json:"data"`
NextCursor string `json:"next_cursor,omitempty"`
HasMore bool `json:"has_more"`
}اعتبارسنجی درخواست: go-playground/validator در برابر Validate() دستنویس حیاتی
به زبان ساده: بعد از Decode بررسی کنید فیلدها معنا دارند: طول SKU، قیمت غیرمنفی و Status شناختهشده. همهٔ خطاها را یکجا و با نشانی فیلد برگردانید. اعتبارسنجی درخواست (Request validation) میتواند Go ساده در Valid باشد یا Struct tagهایی که go-playground/validator میخواند.
بدفهمی رایج: «Validation همان قاعدهٔ کسبوکار است.» Validation شکل یک درخواست را بدون DB بررسی میکند و 422 میدهد. «محصول Archived دوباره Active نمیشود» و «SKU باید یکتا باشد» به حالت ذخیرهشده وابستهاند؛ جای آنها Service یا DB است و شکستشان 409 است. مخلوط کردن اینها SQL را وارد Validator و بررسی شکل را وارد Service میکند.
تعریف: سبک دستنویس از رابط Validator در نوشتهٔ Ryer پیروی میکند: Valid(ctx context.Context) (problems map[string]string). این فصل []validation.Violation{Pointer, Detail} میدهد تا مستقیم به errors در RFC 9457 با اشارهگر JSON (JSON Pointer، RFC 6901) نگاشت شود. سبک Tag از validator.New(validator.WithRequiredStructEnabled()) استفاده میکند؛ README میگوید "highly recommended ... opt-in to new behaviour that will become the default behaviour in v11+". با RegisterTagNameFunc نام JSON گزارش میشود و validator.ValidationErrors به همان Violation تبدیل میشود. طول در هر دو روش برحسب کاراکتر است؛ مستند میگوید "the string length is at most that number of characters". بنابراین کد دستی utf8.RuneCountInString دارد، نه len. فیلد price_cents از نوع *int64 با required است: نبودن آن یا حذف با Merge-patch null به 422 با "is required" میرسد، نه صفر بیصدا. تست برابری دو روش را حتی برای ورودی غیر ASCII ثابت میکند.
1 decode {"sku":"AB","name":"","price_cents":-1,"currency":"eur","status":"sold"} ok: valid JSON
2 Valid /sku must be at least 3 · /name is required · /price_cents must be at least 0
/currency must be upper case · /status must be one of: draft active archived
3 422 application/problem+json, type .../validation, errors[5]
4 service SKU unique? archived frozen? -> 409 if not (business rules, not validation)سناریوی واقعی: فرم همهٔ خطاها را در یک ارسال میخواهد؛ موبایل با /tags/2 فیلد دقیق را روشن میکند؛ شریک تجاری قالب یکسان در همهٔ Endpointها میخواهد؛ قاعدهٔ وابسته به طرح Tenant میتواند اطلاعات لازم را از ctx در Valid بگیرد.
Valid(ctx) دستنویس | Tagهای go-playground/validator | |
|---|---|---|
| وابستگی | فقط Stdlib | github.com/go-playground/validator/v10؛ اینجا v10.30.1 |
| محل دیدن قاعده | کد Go، قابل Debug | رشتهٔ Tag مثل required,min=3,max=32 |
| قاعدهٔ چندفیلدی | if ساده | required_if، gtfield و تابع سفارشی |
| قاعدهٔ وابسته به Context | پارامتر ctx | StructCtx و Validator سفارشی |
| پیام خطا | انتخاب شما | ساخت از FieldError.Tag()/Param() یا Translation |
| سرعت نوشتن قواعد زیاد | کمتر | بیشتر |
| مصرفکننده | الگوی Mat Ryer و سرویسهای Stdlib-first | Validator پیشفرض Binding در Gin |
راهحل / نحوهٔ استفاده: در هر سرویس یک سبک انتخاب و خروجی را به یک Violation تبدیل کنید. رشتهٔ خطای خود Validator را مستقیم به کلاینت ندهید.
// Package validation holds the one type both validation styles produce, a
// Violation addressed by a JSON Pointer, and the tag-based style built on
// github.com/go-playground/validator/v10.
package validation
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/go-playground/validator/v10"
)
// Violation is one problem with one field of the request body. Pointer is an
// RFC 6901 JSON Pointer such as "/price_cents" or "/tags/2".
type Violation struct {
Pointer string `json:"pointer"`
Detail string `json:"detail"`
}
// Tags validates structs by their `validate:"..."` tags and reports fields by
// their JSON names, not their Go names.
type Tags struct {
v *validator.Validate
}
// NewTags builds the validator once; it caches struct metadata, so share it.
func NewTags() *Tags {
v := validator.New(validator.WithRequiredStructEnabled())
v.RegisterTagNameFunc(func(f reflect.StructField) string {
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if name == "-" {
return ""
}
return name
})
return &Tags{v: v}
}
// Struct returns nil or the list of violations for s.
func (t *Tags) Struct(s any) []Violation {
err := t.v.Struct(s)
if err == nil {
return nil
}
var ves validator.ValidationErrors
if !errors.As(err, &ves) {
// InvalidValidationError: a programming error (nil or non-struct).
panic(err)
}
out := make([]Violation, 0, len(ves))
for _, fe := range ves {
out = append(out, Violation{Pointer: pointer(fe.Namespace()), Detail: message(fe)})
}
return out
}
// pointer turns validator's namespace "productWrite.tags[2]" into "/tags/2".
func pointer(ns string) string {
_, rest, _ := strings.Cut(ns, ".")
rest = strings.NewReplacer("[", ".", "]", "").Replace(rest)
return "/" + strings.ReplaceAll(rest, ".", "/")
}
func message(fe validator.FieldError) string {
switch fe.Tag() {
case "required":
return "is required"
case "min", "gte":
return fmt.Sprintf("must be at least %s", fe.Param())
case "max", "lte":
return fmt.Sprintf("must be at most %s", fe.Param())
case "oneof":
return fmt.Sprintf("must be one of: %s", fe.Param())
case "len":
return fmt.Sprintf("must have length %s", fe.Param())
case "uppercase":
return "must be upper case"
}
return "failed rule " + fe.Tag()
}package dto
import (
"slices"
"strings"
"testing"
"academy/rest-api-project/validation"
)
// Both validation styles must report the same JSON pointers and messages for
// the same body, so either can back the 422 problem response.
func TestHandWrittenAndTagValidationAgree(t *testing.T) {
tags := validation.NewTags()
bodies := []ProductWrite{
{},
{SKU: "AB", Name: "x", PriceCents: Cents(-5), Currency: "eur", Status: "sold", Tags: []string{"ok", ""}},
{SKU: "MUG-1", Name: "Mug", PriceCents: Cents(900), Currency: "EUR", Status: "active"},
}
// Non-ASCII: limits count characters, not bytes (validator doc: "the number
// of characters"). "éé" is 2 characters (4 bytes): too short; 101 "é" are
// 101 characters (202 bytes): within the 200 limit.
bodies = append(bodies,
ProductWrite{SKU: "éé", Name: "Tasse", PriceCents: Cents(900), Currency: "EUR", Status: "active"},
ProductWrite{SKU: "TAS-1", Name: strings.Repeat("é", 101), PriceCents: Cents(900), Currency: "EUR", Status: "active"},
ProductWrite{SKU: "TAS-2", Name: "Tasse", PriceCents: Cents(900), Currency: "EUR", Status: "active", Tags: []string{strings.Repeat("ü", 30)}},
)
for i, b := range bodies {
hand := b.Valid(t.Context())
byTag := tags.Struct(b)
if !slices.Equal(hand, byTag) {
t.Errorf("body %d:\n hand %v\n tags %v", i, hand, byTag)
}
}
}
func TestNonASCIIIsCountedInCharacters(t *testing.T) {
short := ProductWrite{SKU: "éé", Name: "Tasse", PriceCents: Cents(900), Currency: "EUR", Status: "active"}
if v := short.Valid(t.Context()); len(v) != 1 || v[0].Pointer != "/sku" {
t.Fatalf("2-character SKU: %v", v)
}
long := ProductWrite{SKU: "TAS-1", Name: strings.Repeat("é", 101), PriceCents: Cents(900), Currency: "EUR", Status: "active"}
if v := long.Valid(t.Context()); v != nil {
t.Fatalf("101-character name: %v", v)
}
}پوشش خطا: Problem Details در RFC 9457 حیاتی
به زبان ساده: پوشش خطا (Error envelope) برای همهٔ خطاهای API یک شکل JSON دارد و با Content-Type: application/problem+json میآید: URI نوع خطا در type، عنوان کوتاه title، status، توضیح اختیاری همین رخداد در detail، مسیر instance و عضوهای اضافه مثل errors و request_id.
بدفهمی رایج: «کلاینت باید متن پیام را بخواند.» RFC 9457 میگوید: "Consumers SHOULD NOT parse the "detail" member for information; extensions are more suitable and less error-prone ways to obtain such information." تصمیم کلاینت برحسب type و HTTP status است، نه متن. وضعیت بدنه هم جای وضعیت واقعی را نمیگیرد: "Generators MUST use the same status code in the actual HTTP response".
تعریف: شیء Problem Details عضوهای type، title، status، detail و instance دارد. type پیشفرض about:blank است که "indicates that the problem has no additional semantics beyond that of the HTTP status code"؛ در این حالت Title هم "SHOULD be the same as the recommended HTTP status phrase". عضو افزوده (Extension member) مجاز است و کلاینت عضو ناشناخته را "MUST ignore". مثال Validation در خود RFC آرایهٔ errors با detail و JSON Pointer در pointer دارد؛ همین را استفاده میکنیم. Problem Details "are not a debugging tool for the underlying implementation": Stack trace، SQL و نام Host داخلی نباید در پاسخ باشند.
1 handler gets product.ErrVersionMismatch
2 writeError: errors.Is(...) -> problem.New(412, "stale-version", "Resource changed since you read it", hint)
3 problem.Write: Content-Type application/problem+json, Cache-Control no-store, status 412
4 body {"type":"https://api.example.test/problems/stale-version","title":...,"status":412,
"instance":"/v1/products/prd_...","request_id":"4fc986c41e92388b"}
5 client: switch on type -> re-GET, re-apply, retryسناریوی واقعی: کلاینت TypeScript تولیدشده همهٔ پاسخهای غیر 2xx را به ProblemError تبدیل میکند؛ پشتیبانی با request_id مشتری Log را پیدا میکند؛ UI هر pointer را به فیلد فرم وصل میکند؛ Gateway نوع rate-limited را بدون شکستن کلاینت اضافه میکند.
| API | شکل خطا | کد قابل خواندن برای ماشین |
|---|---|---|
| این فصل | RFC 9457 + errors[] + request_id | URI در type |
| Stripe | {"error": {"type", "code", "message", "param", ...} } | type + code |
| Google AIPs، AIP-193 | google.rpc.Status همراه Details | Canonical code + ErrorInfo.reason |
| Validation پیشفرض Laravel | {"message", "errors": {"field": ["..."]} }، 422 | کلید فیلد |
| JSON:API | {"errors": [{"status","code","title","source": {"pointer"} } ] } | code |
راهحل / نحوهٔ استفاده: یک بستهٔ Constructor، یک تابع Write و یک نگاشت writeError داشته باشید؛ برای هر URI نوع، صفحهٔ توضیح ثبت کنید.
// Package problem writes RFC 9457 Problem Details: the one error envelope
// every endpoint of the API returns.
package problem
import (
"encoding/json"
"net/http"
"academy/rest-api-project/validation"
)
// MediaType is the content type registered by RFC 9457.
const MediaType = "application/problem+json"
// TypeBase is where the human-readable documentation of each problem type
// lives. Clients switch on Type, never on Title or Detail.
const TypeBase = "https://api.example.test/problems/"
// Problem is the RFC 9457 object plus two extension members: errors (one
// entry per invalid field) and request_id (to find the log line).
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Errors []validation.Violation `json:"errors,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
// New builds a problem whose type is TypeBase+slug, or about:blank when slug
// is empty (then the title must be the status phrase, per RFC 9457 4.2.1).
func New(status int, slug, title, detail string) *Problem {
p := &Problem{Type: "about:blank", Title: http.StatusText(status), Status: status, Detail: detail}
if slug != "" {
p.Type = TypeBase + slug
p.Title = title
}
return p
}
// Validation is the 422 problem with one entry per violation.
func Validation(v []validation.Violation) *Problem {
p := New(http.StatusUnprocessableEntity, "validation", "Request body failed validation", "")
p.Errors = v
return p
}
// Write sends p with the same status in the header and the body, as the RFC
// requires ("Generators MUST use the same status code").
func Write(w http.ResponseWriter, r *http.Request, p *Problem) {
if p.Instance == "" {
p.Instance = r.URL.Path
}
if p.RequestID == "" {
p.RequestID = w.Header().Get("X-Request-ID") // set by the request-id middleware
}
w.Header().Set("Content-Type", MediaType)
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}کدهای وضعیت (Status codes) حیاتی
به زبان ساده: کد وضعیت (Status code) اولین چیزی است که کلاینت، Proxy، کتابخانهٔ Retry و داشبورد میخواند. بپرسید چه کسی باید کاری بکند: 2xx کاری لازم ندارد، 4xx کلاینت باید چیزی را تغییر دهد، 5xx سمت سرور شکست خورده و شاید Retry کمک کند.
بدفهمی رایج: «همهٔ خطاهای کلاینت را 400 بدهیم سادهتر است.» JSON خراب (400)، قیمت منفی در JSON سالم (422)، نسخهٔ قدیمی (412) و نبودن If-Match (428) راهحل یکسان ندارند. Retry library هم با 409 و 429 رفتار خاص دارد. از آن طرف کد اختراعی یا 500 برای Not found هم غلط است.
تعریف: جدول، کدها و شرط دقیقشان را در snippetها نشان میدهد. در net/http ثابتهایی مثل http.StatusUnprocessableEntity و http.StatusPreconditionRequired داریم؛ سورس status.go بخش RFC هرکدام را مشخص کرده است.
1 bytes arrive Content-Type? 415 · too big? 413 · not JSON / unknown field? 400
2 JSON decoded rules broken? 422 with errors[]
3 If-Match missing? 428 · stale? 412
4 service no such id? 404 · SKU taken / frozen status? 409
5 success 201 + Location (create) · 200 (read, update) · 204 (delete) · 304 (not modified)
6 overload, failure 429 + Retry-After · 503 not ready · 500 bug (cause logged, not sent)سناریوی واقعی: Retry روی 503 و 429 انجام میشود ولی روی 422 نه؛ CDN ممکن است 404 را Cache کند؛ هشدار نرخ 5xx نباید با Validation روشن شود؛ 412 در UI پیام «شخص دیگری ویرایش کرده» میسازد.
| کد | نام، از RFC 9110 مگر خلافش ذکر شود | شرط این API | کار کلاینت |
|---|---|---|---|
| 200 | OK | Read، PUT یا PATCH موفق | از Body استفاده کند |
| 201 | Created | POST ساخته؛ Location و ETag دارد | ID را نگه دارد یا Location را دنبال کند |
| 204 | No Content | DELETE موفق | هیچ |
| 304 | Not Modified | If-None-Match با ETag فعلی برابر است | نسخهٔ Cache را استفاده کند |
| 400 | Bad Request | JSON خراب، فیلد ناشناخته، نوع غلط، Query/Cursor خراب یا دو مقدار JSON | درخواست را اصلاح کند |
| 404 | Not Found | ID محصول یا مسیر وجود ندارد | متوقف شود یا دوباره List بگیرد |
| 405 | Method Not Allowed | مسیر هست، Method نیست؛ روشها در Allow هستند | Method مجاز بفرستد |
| 409 | Conflict | SKU تکراری، تغییر Status ممنوع یا Idempotency-Key در حال اجرا | داده را عوض کند؛ برای In-flight بعداً Retry کند |
| 412 | Precondition Failed | If-Match با ETag فعلی نمیخواند | دوباره GET، اعمال تغییر و Retry |
| 413 | Content Too Large | بدنه بالاتر از API_MAX_BODY_BYTES؛ http.MaxBytesError | کمتر بفرستد |
| 415 | Unsupported Media Type | نوع جز application/json یا برای PATCH جز application/merge-patch+json | نوع درست بفرستد |
| 422 | Unprocessable Content | JSON سالم با مقدار نامعتبر؛ کلید تکراری با بدنهٔ متفاوت | فیلدهای errors را اصلاح کند |
| 428 | Precondition Required، RFC 6585 | PUT/PATCH/DELETE بدون If-Match | ETag را بفرستد |
| 429 | Too Many Requests، RFC 6585 | Rate limiting hook رد کرده؛ Retry-After تنظیم است | صبر و سپس Retry |
| 500 | Internal Server Error | خطای نگاشتنشده یا Panic | فقط اگر Idempotent است بعداً Retry |
| 503 | Service Unavailable | /readyz هنگام Shutdown یا خرابی وابستگی | Load balancer مقصد دیگری انتخاب کند |
راهحل / نحوهٔ استفاده: نگاشت خطا به کد فقط در writeError باشد. هر کد را یکبار End-to-end تست کنید؛ مثل TestRequestErrorsAreProblems و TestCRUDLifecycle.
الگوی مخزن: یک Interface برای هر Aggregate حیاتی
به زبان ساده: سرویس بهجای SQL با رابط کوچک service.Repository حرف میزند؛ همان پنج عملیاتی که برای محصول لازم دارد. یک پیادهسازی PostgreSQL و یک پیادهسازی حافظهای آن را اجرا میکنند تا همان سرویس در تست و Production کار کند. این الگوی مخزن (Repository pattern) است.
بدفهمی رایج: «یک Repository[T] عمومی با FindAll، FindBy(map) و Save همهٔ جدولها را پوشش میدهد.» این کار زبان Query را با FindBy(map[string]any{"status": ...}) به Service نشت میدهد، Keyset pagination و Optimistic locking را خوب بیان نمیکند و هر تجمیع (Aggregate) را به جدول تقلیل میدهد. یک رابط برای هر Aggregate یا Interface per aggregate باید زبان Use case را حرف بزند. بدفهمی دیگر: «بستهٔ Repository رابط را تعریف میکند.» در Go مصرفکننده رابط را تعریف میکند؛ service مالک Repository است و pgrepo فقط متدهای لازم را دارد.
تعریف: Repository واسطهٔ Domain و Storage برای یک Aggregate root در معنای DDD است؛ ببینید Repositories. متدها نوع و خطای Domain مثل product.ErrNotFound، ErrSKUTaken و ErrVersionMismatch دارند، نه sql.ErrNoRows یا SQLSTATE. متد List، Limit+1 ردیف میدهد تا سرویس بدون COUNT وجود صفحهٔ بعد را بفهمد. بررسی زمان کامپایل var _ service.Repository = (*memrepo.Repo)(nil) در تست هر دو پیادهسازی هست.
1 service.Replace(ctx, id, ifVersion=1, draft)
2 repo.Get(ctx, id) -> product v1
3 rule: CanTransition(v1.Status, draft.Status)
4 repo.Update(ctx, v2, expected=1)
pgrepo: UPDATE ... WHERE id = $1 AND version = $9 -> 1 row
memrepo: lock; cur.Version == 1? store -> ok
5 concurrent writer with expected=1 -> 0 rows -> ErrVersionMismatch -> 412سناریوی واقعی: تست قاعدهٔ قیمت با memrepo در میکروثانیه اجرا میشود؛ یک Aggregate از PostgreSQL به DynamoDB میرود بدون تغییر Handler؛ Read model از Replica سرو میشود؛ Decorator ثبت Audit دور هر Repository قرار میگیرد.
| انتخاب | وابستگی Service | مناسب برای | هزینه |
|---|---|---|---|
*sql.DB داخل Service | متن SQL و خطای Driver | ابزار کوچک | Unit test بدون DB ندارید |
Repository[T] عمومی | Query-by-map | پنل CRUD | نشت جزئیات، Type ضعیف، بدون Keyset |
| Interface per aggregate، این فصل | متد و خطای Domain | سرویس دارای قاعده | یک Interface و دو پیادهسازی |
| sqlc / Query تولیدشده + Repo نازک | Query تایپدار؛ README: "sqlc generates type-safe code from SQL" | تیم SQL-first | مرحلهٔ Generation |
| ORM پشت Repo؛ GORM: "The fantastic ORM library for Golang"؛ ent: "An Entity Framework For Go" | نوع ORM فقط داخل Repo | تیم علاقهمند به ORM | شناخت رفتار ORM؛ دامها |
راهحل / نحوهٔ استفاده: پیادهسازی حافظه همان الگوریتم Keyset نسخهٔ SQL را اجرا میکند تا Pagination بدون DB تست شود. نسخهٔ PostgreSQL از database/sql و ORDER BY با Allow-list استفاده و SQLSTATE 23505 را از متد SQLState() نگاشت میکند. هم *pgconn.PgError در pgx با func (pe *PgError) SQLState() string و هم *pq.Error در lib/pq با func (e *Error) SQLState() string آن را دارند. tags از نوع jsonb است و به شکل متن JSON ارسال میشود؛ بنابراین مستقل از Driver است، برخلاف text[] که Array encoding مخصوص Driver میخواهد. هر دو Repo برای Readiness متد Ping دارند. تست TestTagsRoundTrip بدون سرور PostgreSQL از Driver جعلی کوچک database/sql استفاده میکند که دقیقاً ستونهای SQL را نگه میدارد؛ جاافتادن ستون از INSERT، UPDATE یا SELECT تست را میشکند. Pool، Transaction و جزئیات pgx در database/sql & pgx است.
// Package memrepo is an in-memory service.Repository: same contract as the
// PostgreSQL one, used by unit and end-to-end tests and by the demo binary.
package memrepo
import (
"context"
"slices"
"sync"
"academy/rest-api-project/product"
)
// Repo is safe for concurrent use.
type Repo struct {
mu sync.RWMutex
byID map[string]product.Product
bySKU map[string]string
}
// New returns an empty repository.
func New() *Repo {
return &Repo{byID: map[string]product.Product{}, bySKU: map[string]string{}}
}
func (r *Repo) Insert(ctx context.Context, p product.Product) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
if _, taken := r.bySKU[p.SKU]; taken {
return product.ErrSKUTaken
}
r.byID[p.ID] = clone(p)
r.bySKU[p.SKU] = p.ID
return nil
}
func (r *Repo) Get(ctx context.Context, id string) (product.Product, error) {
if err := ctx.Err(); err != nil {
return product.Product{}, err
}
r.mu.RLock()
defer r.mu.RUnlock()
p, ok := r.byID[id]
if !ok {
return product.Product{}, product.ErrNotFound
}
return clone(p), nil
}
func (r *Repo) Update(ctx context.Context, p product.Product, expected int64) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
cur, ok := r.byID[p.ID]
if !ok {
return product.ErrNotFound
}
if cur.Version != expected {
return product.ErrVersionMismatch
}
if owner, taken := r.bySKU[p.SKU]; taken && owner != p.ID {
return product.ErrSKUTaken
}
delete(r.bySKU, cur.SKU)
r.bySKU[p.SKU] = p.ID
r.byID[p.ID] = clone(p)
return nil
}
func (r *Repo) Delete(ctx context.Context, id string, expected int64) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
cur, ok := r.byID[id]
if !ok {
return product.ErrNotFound
}
if cur.Version != expected {
return product.ErrVersionMismatch
}
delete(r.byID, id)
delete(r.bySKU, cur.SKU)
return nil
}
// List filters, sorts by (field, id) and seeks past the cursor: the same
// keyset algorithm the SQL version runs in the database.
func (r *Repo) List(ctx context.Context, q product.ListQuery) ([]product.Product, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
r.mu.RLock()
var rows []product.Product
for _, p := range r.byID {
if match(p, q) {
rows = append(rows, clone(p))
}
}
r.mu.RUnlock()
sign := 1
if q.Desc {
sign = -1
}
slices.SortFunc(rows, func(a, b product.Product) int {
return sign * product.Compare(product.CursorAfter(a), product.CursorAfter(b), q.Sort)
})
out := rows[:0]
for _, p := range rows {
if q.After != nil && sign*product.Compare(product.CursorAfter(p), *q.After, q.Sort) <= 0 {
continue
}
out = append(out, p)
if len(out) == q.Limit+1 {
break
}
}
return out, nil
}
// Ping lets the readiness probe ask the store if it is usable.
func (r *Repo) Ping(ctx context.Context) error { return ctx.Err() }
func match(p product.Product, q product.ListQuery) bool {
if q.Status != "" && p.Status != q.Status {
return false
}
if q.MinPrice != nil && p.PriceCents < *q.MinPrice {
return false
}
if q.MaxPrice != nil && p.PriceCents > *q.MaxPrice {
return false
}
return true
}
func clone(p product.Product) product.Product {
p.Tags = slices.Clone(p.Tags)
return p
}// Package pgrepo is the PostgreSQL service.Repository on database/sql. It
// imports no driver: main registers one (pgx's stdlib adapter, for example).
package pgrepo
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"academy/rest-api-project/product"
)
// Schema is the table the repository expects (normally a migration file).
const Schema = `
CREATE TABLE products (
id text PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price_cents bigint NOT NULL CHECK (price_cents >= 0),
currency char(3) NOT NULL,
status text NOT NULL,
tags jsonb NOT NULL DEFAULT '[]',
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX products_created_id ON products (created_at, id);
CREATE INDEX products_price_id ON products (price_cents, id);
CREATE INDEX products_name_id ON products (name, id);`
// Repo implements service.Repository.
type Repo struct {
db *sql.DB
}
// New takes the pool; the caller owns its lifetime.
func New(db *sql.DB) *Repo { return &Repo{db: db} }
// Ping backs the readiness probe, like memrepo.Repo.Ping.
func (r *Repo) Ping(ctx context.Context) error { return r.db.PingContext(ctx) }
func (r *Repo) Get(ctx context.Context, id string) (product.Product, error) {
row := r.db.QueryRowContext(ctx, `SELECT `+columns+` FROM products WHERE id = $1`, id)
p, err := scan(row)
if errors.Is(err, sql.ErrNoRows) {
return product.Product{}, product.ErrNotFound
}
return p, err
}
// Update is optimistic concurrency in one statement: the WHERE clause on
// version makes a stale write affect zero rows.
func (r *Repo) Update(ctx context.Context, p product.Product, expected int64) error {
res, err := r.db.ExecContext(ctx, `
UPDATE products SET sku = $2, name = $3, price_cents = $4, currency = $5,
status = $6, version = $7, updated_at = $8, tags = $10
WHERE id = $1 AND version = $9`,
p.ID, p.SKU, p.Name, p.PriceCents, p.Currency, p.Status, p.Version, p.UpdatedAt, expected, tagsJSON(p.Tags))
if err != nil {
return mapErr(err)
}
if n, _ := res.RowsAffected(); n == 0 {
if _, err := r.Get(ctx, p.ID); err != nil {
return err // ErrNotFound
}
return product.ErrVersionMismatch
}
return nil
}
func (r *Repo) Insert(ctx context.Context, p product.Product) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO products (id, sku, name, price_cents, currency, status, tags, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
p.ID, p.SKU, p.Name, p.PriceCents, p.Currency, p.Status, tagsJSON(p.Tags), p.Version, p.CreatedAt, p.UpdatedAt)
return mapErr(err)
}
func (r *Repo) Delete(ctx context.Context, id string, expected int64) error {
res, err := r.db.ExecContext(ctx, `DELETE FROM products WHERE id = $1 AND version = $2`, id, expected)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
if _, err := r.Get(ctx, id); err != nil {
return err
}
return product.ErrVersionMismatch
}
return nil
}
func (r *Repo) List(ctx context.Context, q product.ListQuery) ([]product.Product, error) {
query, args := BuildList(q)
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []product.Product
for rows.Next() {
p, err := scan(rows)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// sortColumns is an allow-list: user input never becomes SQL text.
var sortColumns = map[product.SortField]string{
product.SortCreatedAt: "created_at",
product.SortPrice: "price_cents",
product.SortName: "name",
}
// BuildList renders filter + keyset seek + order + limit. The row-value
// comparison (col, id) > ($n, $m) matches the (col, id) index exactly.
func BuildList(q product.ListQuery) (string, []any) {
col, ok := sortColumns[q.Sort]
if !ok {
col = "created_at"
}
var where []string
var args []any
arg := func(v any) string { args = append(args, v); return fmt.Sprintf("$%d", len(args)) }
if q.Status != "" {
where = append(where, "status = "+arg(string(q.Status)))
}
if q.MinPrice != nil {
where = append(where, "price_cents >= "+arg(*q.MinPrice))
}
if q.MaxPrice != nil {
where = append(where, "price_cents <= "+arg(*q.MaxPrice))
}
op, dir := ">", "ASC"
if q.Desc {
op, dir = "<", "DESC"
}
if c := q.After; c != nil {
var v any = c.CreatedAt
switch q.Sort {
case product.SortPrice:
v = c.PriceCents
case product.SortName:
v = c.Name
}
where = append(where, fmt.Sprintf("(%s, id) %s (%s, %s)", col, op, arg(v), arg(c.ID)))
}
var b strings.Builder
b.WriteString("SELECT " + columns + " FROM products")
if len(where) > 0 {
b.WriteString(" WHERE " + strings.Join(where, " AND "))
}
fmt.Fprintf(&b, " ORDER BY %s %s, id %s LIMIT %s", col, dir, dir, arg(q.Limit+1))
return b.String(), args
}
// tags is stored as jsonb and sent as JSON text: driver-independent, unlike
// text[], whose array encoding differs between pgx and lib/pq.
const columns = "id, sku, name, price_cents, currency, status, tags, version, created_at, updated_at"
func tagsJSON(tags []string) string {
if tags == nil {
tags = []string{}
}
b, _ := json.Marshal(tags)
return string(b)
}
type scanner interface{ Scan(dest ...any) error }
func scan(s scanner) (product.Product, error) {
var p product.Product
var tags []byte
err := s.Scan(&p.ID, &p.SKU, &p.Name, &p.PriceCents, &p.Currency, &p.Status, &tags, &p.Version, &p.CreatedAt, &p.UpdatedAt)
if err == nil && len(tags) > 0 {
err = json.Unmarshal(tags, &p.Tags)
}
return p, err
}
// mapErr turns a unique violation (SQLSTATE 23505) into the domain error.
// pgx's *pgconn.PgError and lib/pq's *pq.Error both expose SQLState().
func mapErr(err error) error {
var st interface{ SQLState() string }
if errors.As(err, &st) && st.SQLState() == "23505" {
return product.ErrSKUTaken
}
return err
}لایهٔ سرویس (Service layer) حیاتی
به زبان ساده: لایهٔ سرویس (Service layer) محل Use caseهای Create، Get، List، Replace و Delete و قواعد وابسته به حالت ذخیرهشده است. Go سادهای است که Handler HTTP، متد gRPC، دستور CLI یا Queue consumer میتوانند صدا بزنند.
بدفهمی رایج: «Service فقط Boilerplate برای رد کردن فراخوانی به Repository است.» برای Get شاید؛ اما در Replace بررسی نسخه، قاعدهٔ Status و Timestamp اینجا هستند. Transaction یا نوشتن Outbox هم همینجا قرار میگیرد. حذف این لایه قواعد را به Handler میبرد؛ سپس Consumer یا CLI مدیریتی همانها را متفاوت پیاده میکند.
تعریف: Service یک Struct با Constructor است که همهٔ وابستگیها را میگیرد: service.New(repo, now, newID). متدها ابتدا ctx و سپس ورودی Domain میگیرند و خروجی و خطای Domain میدهند. رابط مصرفی را خودش مالک است و هرگز net/http را Import نمیکند. PUT و PATCH هر دو به Replace(ctx, id, ifVersion, draft) میرسند تا قواعدشان یکسان بماند.
1 handler PATCH merge -> decode -> Valid -> svc.Replace(ctx, id, ifVersion, draft)
2 handler PUT decode -> Valid ----------> svc.Replace(ctx, id, ifVersion, draft)
3 CLI "archive" draft.Status = archived --> svc.Replace(ctx, id, ifVersion, draft)
4 Replace: Get -> version check -> CanTransition -> stamp UpdatedAt -> Version+1 -> repo.Updateسناریوی واقعی: Job ورود محصول باید همان قاعدهٔ «Archived ثابت است» API را رعایت کند؛ تغییر قیمت و Audit باید در یک Transaction نوشته شوند؛ رویداد ProductRepriced از یک نقطه از طریق Outbox منتشر شود؛ Clock تزریق شود تا Timestamp قابل Assert باشد.
| منطق | محل | مثال |
|---|---|---|
| شکل یک درخواست | Valid در DTO | price_cents >= 0 |
| پروتکل HTTP | Handler | Parse کردن If-Match، پاسخ 201 + Location |
| قواعد وابسته به حالت | Service | Archived ثابت است؛ نسخه باید بخواند |
| قاعدهٔ همیشگی یک مقدار (Invariant) | Domain، product | CanTransition، Status.Valid |
| یکتایی زیر همزمانی | Database | UNIQUE (sku) با نگاشت به ErrSKUTaken |
راهحل / نحوهٔ استفاده: بستهٔ Domain، Aggregate، خطاهایش، قاعدهٔ گذار و ترتیب Keyset را نگه میدارد؛ Service آنها را مصرف میکند.
// Package product is the domain model of the chapter's API: one aggregate,
// its invariants and the errors the rest of the code maps to HTTP.
package product
import (
"errors"
"time"
)
// Status is the lifecycle state of a product.
type Status string
const (
StatusDraft Status = "draft"
StatusActive Status = "active"
StatusArchived Status = "archived"
)
// Valid reports whether s is one of the known states.
func (s Status) Valid() bool {
switch s {
case StatusDraft, StatusActive, StatusArchived:
return true
}
return false
}
// Product is the aggregate root. Version increments on every change and is
// what the HTTP layer exposes as the ETag.
type Product struct {
ID string
SKU string
Name string
PriceCents int64
Currency string
Status Status
Tags []string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// Draft holds the client-writable fields, shared by create, replace and patch.
type Draft struct {
SKU string
Name string
PriceCents int64
Currency string
Status Status
Tags []string
}
// Domain errors. Callers compare with errors.Is; the HTTP layer maps them to
// status codes in exactly one place.
var (
ErrNotFound = errors.New("product not found")
ErrSKUTaken = errors.New("sku already exists")
ErrVersionMismatch = errors.New("version mismatch")
ErrInvalidTransition = errors.New("invalid status transition")
)
// CanTransition encodes the business rule that an archived product is frozen:
// it can only stay archived.
func CanTransition(from, to Status) bool {
if from == StatusArchived {
return to == StatusArchived
}
return to.Valid()
}
// SortField names the columns a list can be ordered by.
type SortField string
const (
SortCreatedAt SortField = "created_at"
SortPrice SortField = "price"
SortName SortField = "name"
)
// ListQuery is a filtered, sorted, keyset-paginated read of the collection.
type ListQuery struct {
Status Status // empty: any status
MinPrice *int64 // inclusive, cents
MaxPrice *int64 // inclusive, cents
Sort SortField
Desc bool
After *Cursor // nil: first page
Limit int
}
// Cursor is the keyset position: the sort value and the id of the last row
// of the previous page. Only the field that matches Sort is meaningful.
type Cursor struct {
CreatedAt time.Time `json:"c,omitzero"`
PriceCents int64 `json:"p,omitempty"`
Name string `json:"n,omitempty"`
ID string `json:"i"`
}
// CursorAfter builds the cursor that continues after p.
func CursorAfter(p Product) Cursor {
return Cursor{CreatedAt: p.CreatedAt, PriceCents: p.PriceCents, Name: p.Name, ID: p.ID}
}
// Only keeps the field the list is sorted by (and the id), so the page token
// carries nothing else about the row.
func (c Cursor) Only(field SortField) Cursor {
out := Cursor{ID: c.ID}
switch field {
case SortPrice:
out.PriceCents = c.PriceCents
case SortName:
out.Name = c.Name
default:
out.CreatedAt = c.CreatedAt
}
return out
}
// Compare orders a and b by field, breaking ties by ID so the order is total,
// which keyset pagination requires.
func Compare(a, b Cursor, field SortField) int {
var c int
switch field {
case SortPrice:
c = cmpInt(a.PriceCents, b.PriceCents)
case SortName:
c = cmpString(a.Name, b.Name)
default:
c = a.CreatedAt.Compare(b.CreatedAt)
}
if c != 0 {
return c
}
return cmpString(a.ID, b.ID)
}
func cmpInt(a, b int64) int {
switch {
case a < b:
return -1
case a > b:
return 1
}
return 0
}
func cmpString(a, b string) int {
switch {
case a < b:
return -1
case a > b:
return 1
}
return 0
}// Package service is the application layer: use cases on the product
// aggregate. It knows nothing about HTTP or SQL; it owns the Repository
// interface it needs (the consumer defines the interface).
package service
import (
"context"
"fmt"
"slices"
"time"
"academy/rest-api-project/product"
)
// Repository is the persistence port for one aggregate. Implementations:
// memrepo (tests, demos) and pgrepo (PostgreSQL).
type Repository interface {
Insert(ctx context.Context, p product.Product) error
Get(ctx context.Context, id string) (product.Product, error)
// Update stores p only if the stored version equals expected.
Update(ctx context.Context, p product.Product, expected int64) error
Delete(ctx context.Context, id string, expected int64) error
// List returns up to q.Limit+1 rows so the caller can tell if more exist.
List(ctx context.Context, q product.ListQuery) ([]product.Product, error)
}
// Service wires the use cases to their dependencies, all passed in.
type Service struct {
repo Repository
now func() time.Time
newID func() string
}
// New is the only way to build a Service: dependency injection via the
// constructor, no globals, no container.
func New(repo Repository, now func() time.Time, newID func() string) *Service {
return &Service{repo: repo, now: now, newID: newID}
}
// Create stores a new product at version 1.
func (s *Service) Create(ctx context.Context, d product.Draft) (product.Product, error) {
at := s.now().UTC()
p := apply(product.Product{ID: s.newID(), Version: 1, CreatedAt: at}, d, at)
if err := s.repo.Insert(ctx, p); err != nil {
return product.Product{}, fmt.Errorf("create %s: %w", d.SKU, err)
}
return p, nil
}
// Get loads one product.
func (s *Service) Get(ctx context.Context, id string) (product.Product, error) {
return s.repo.Get(ctx, id)
}
// Page is one page of a list and the position to continue from.
type Page struct {
Items []product.Product
Next *product.Cursor
}
// List reads one page; q.Limit must already be clamped.
func (s *Service) List(ctx context.Context, q product.ListQuery) (Page, error) {
rows, err := s.repo.List(ctx, q)
if err != nil {
return Page{}, err
}
if len(rows) <= q.Limit {
return Page{Items: rows}, nil
}
rows = rows[:q.Limit]
next := product.CursorAfter(rows[len(rows)-1]).Only(q.Sort)
return Page{Items: rows, Next: &next}, nil
}
// Replace is the single write path for PUT and PATCH: the caller sends the
// full new state and the version it last saw (from If-Match).
func (s *Service) Replace(ctx context.Context, id string, ifVersion int64, d product.Draft) (product.Product, error) {
cur, err := s.repo.Get(ctx, id)
if err != nil {
return product.Product{}, err
}
if cur.Version != ifVersion {
return product.Product{}, product.ErrVersionMismatch
}
if !product.CanTransition(cur.Status, d.Status) {
return product.Product{}, fmt.Errorf("%w: %s -> %s", product.ErrInvalidTransition, cur.Status, d.Status)
}
next := apply(cur, d, s.now().UTC())
next.Version = cur.Version + 1
if err := s.repo.Update(ctx, next, cur.Version); err != nil {
return product.Product{}, err
}
return next, nil
}
// Delete removes a product if the client saw its latest version.
func (s *Service) Delete(ctx context.Context, id string, ifVersion int64) error {
return s.repo.Delete(ctx, id, ifVersion)
}
func apply(p product.Product, d product.Draft, at time.Time) product.Product {
p.SKU, p.Name, p.PriceCents, p.Currency, p.Status = d.SKU, d.Name, d.PriceCents, d.Currency, d.Status
p.Tags = slices.Clone(d.Tags)
p.UpdatedAt = at
return p
}package service_test
import (
"errors"
"testing"
"time"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
func newService() *service.Service {
at := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
n := 0
return service.New(memrepo.New(),
func() time.Time { at = at.Add(time.Second); return at },
func() string { n++; return "prd_" + string(rune('a'+n-1)) })
}
func TestReplaceRequiresCurrentVersion(t *testing.T) {
s := newService()
ctx := t.Context()
p, err := s.Create(ctx, product.Draft{SKU: "MUG-1", Name: "Mug", PriceCents: 900, Currency: "EUR", Status: product.StatusDraft})
if err != nil {
t.Fatal(err)
}
d := product.Draft{SKU: "MUG-1", Name: "Mug", PriceCents: 1200, Currency: "EUR", Status: product.StatusActive}
upd, err := s.Replace(ctx, p.ID, 1, d)
if err != nil || upd.Version != 2 || upd.PriceCents != 1200 {
t.Fatalf("replace: %+v %v", upd, err)
}
// A second client still holding version 1 loses: no lost update.
if _, err := s.Replace(ctx, p.ID, 1, d); !errors.Is(err, product.ErrVersionMismatch) {
t.Fatalf("stale replace: %v", err)
}
}
func TestArchivedIsFrozen(t *testing.T) {
s := newService()
ctx := t.Context()
p, _ := s.Create(ctx, product.Draft{SKU: "OLD", Name: "Old", Currency: "EUR", Status: product.StatusArchived})
_, err := s.Replace(ctx, p.ID, 1, product.Draft{SKU: "OLD", Name: "Old", Currency: "EUR", Status: product.StatusActive})
if !errors.Is(err, product.ErrInvalidTransition) {
t.Fatalf("want ErrInvalidTransition, got %v", err)
}
}
func TestDuplicateSKU(t *testing.T) {
s := newService()
d := product.Draft{SKU: "DUP", Name: "x", Currency: "EUR", Status: product.StatusDraft}
_, _ = s.Create(t.Context(), d)
if _, err := s.Create(t.Context(), d); !errors.Is(err, product.ErrSKUTaken) {
t.Fatalf("want ErrSKUTaken, got %v", err)
}
}تزریق وابستگی با Constructor و الگوی تابع run از Mat Ryer حیاتی
به زبان ساده: تزریق وابستگی با سازنده (Dependency injection via constructors) یعنی هر جزء نیازش را از Constructor بگیرد، نه Global. یک تابع Run بهترتیب Config، Logger، Repository، Service، HTTP handler و Server را میسازد و تنها محل آشنایی با همهٔ نوعهای واقعی است. main آن را صدا میزند و در خطا با کد غیرصفر خارج میشود؛ تست هم همان Run را صدا میزند.
بدفهمی رایج: «Go به DI container مثل wire، fx یا dig نیاز دارد.» برای یک سرویس، ریشهٔ ترکیب (Composition root) چند خط فراخوانی معمولی با بررسی Compiler است. Container برای صدها جزء و Lifecycle مفید است، اما خطاهایی را به Startup میبرد. بدفهمی دوم این است که Setup باید در main باشد؛ آن وقت تست برنامه را اجرا نمیکند و deferهای main با os.Exit اجرا نمیشوند. Ryer میگوید "I wish func main() was func main() error"؛ پس func run(ctx context.Context, w io.Writer, args []string) error و یک main کوچک پیشنهاد میکند.
تعریف: Constructor injection امضای New(deps...) *T دارد؛ اگر فهرست طولانی شد Deps میسازید. الگوی تابع اجرا (Run function pattern) سیستمعامل را به آرگومان تبدیل میکند: os.Args، os.Stdin، os.Stdout، os.Stderr و os.Getenv به شکل func(string) string. دربارهٔ تزریق getenv، Ryer میگوید "beats using t.SetEnv ... because you can continue to run your tests in parallel by calling t.Parallel(), which t.SetEnv doesn’t allow". signal.NotifyContext درون Run قرار میگیرد تا cancel آن واقعاً با Defer اجرا شود؛ اصلاحیهٔ او میگوید از main، "cancel wouldn’t get called".
1 main() app.Run(context.Background(), os.Args, os.Getenv, os.Stdout)
2 Run ctx := signal.NotifyContext(ctx, SIGINT, SIGTERM); defer cancel()
3 cfg := config.Load(getenv); flags from args
4 repo := memrepo.New() | pgrepo.New(db)
5 svc := service.New(repo, time.Now, newID)
6 h := httpapi.NewServer(Deps{Logger, Products: svc, Cursors, Idempotency, Ready})
7 srv.Serve(ln) until ctx done -> graceful shutdown -> return nil
8 test go app.Run(ctx, args, fakeEnv, pipe); wait /readyz; drive with the clientسناریوی واقعی: تست End-to-end اتصال واقعی برنامه را در همان Process اجرا میکند؛ با یک خط Repo حافظهای جای PostgreSQL مینشیند؛ CLI و HTTP یک Constructor سرویس را مصرف میکنند؛ Global جدید چون در Run دیده نمیشود در Review پیدا میشود.
| روش | بررسی Wiring | ورودی قابل تست | زمان استفاده |
|---|---|---|---|
Global و init() | ندارد | نه | برای سرویس هرگز |
Setup در main | Compiler | نه؛ os.Exit و Env واقعی | ابزار دورریختنی |
run(ctx, args, getenv, stdout) error و Constructorها | Compiler | بله | پیشفرض سرویس |
Google wire: "a code generation tool"، "without runtime state or reflection"؛ README: "This project is no longer maintained" | Compiler، کد تولیدشده | بله | کاربران موجود؛ Constructor ساده ترجیح دارد |
Uber fx: "a dependency injection system for Go" / dig: "A reflection based dependency injection toolkit" | Startup | بله، fxtest.New | ماژولهای زیاد با Lifecycle |
راهحل / نحوهٔ استفاده: Run بخش بعد همان Composition root است. app_test.go آن را راه میاندازد، آدرس Listener را از JSON log میخواند، مانند waitForReady در الگوی Ryer منتظر /readyz میماند، Typed client را اجرا و سپس Context را Cancel میکند تا Shutdown تمیز را Assert کند. جزئیات در Mocking with Interfaces & DI است.
package app_test
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"testing"
"time"
"academy/rest-api-project/app"
"academy/rest-api-project/client"
"academy/rest-api-project/dto"
)
// start runs the real program, as main would, and returns its base URL once
// /readyz answers 200.
func start(t *testing.T, env map[string]string) (string, context.CancelFunc, <-chan error) {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
pr, pw := io.Pipe()
done := make(chan error, 1)
go func() {
err := app.Run(ctx, []string{"api", "-addr", "127.0.0.1:0"}, func(k string) string { return env[k] }, pw)
pw.Close()
done <- err
}()
addr := make(chan string, 1)
go func() { // read the log stream; keep draining so logging never blocks
sc := bufio.NewScanner(pr)
for sc.Scan() {
var line struct{ Msg, Addr string }
if json.Unmarshal(sc.Bytes(), &line) == nil && line.Msg == "listening" {
addr <- line.Addr
}
}
}()
var base string
select {
case a := <-addr:
base = "http://" + a
case err := <-done:
t.Fatalf("run exited early: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("server did not start")
}
waitForReady(t, base+"/readyz")
return base, cancel, done
}
func waitForReady(t *testing.T, endpoint string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
resp, err := http.Get(endpoint)
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return
}
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("%s never became ready", endpoint)
}
var env = map[string]string{"API_CURSOR_KEY": "0123456789abcdef", "API_SHUTDOWN_TIMEOUT": "2s"}
func TestRunEndToEnd(t *testing.T) {
base, stop, done := start(t, env)
c := &client.Client{BaseURL: base}
ctx := t.Context()
for i := range 5 {
in := dto.ProductWrite{SKU: fmt.Sprintf("SKU-%d", i), Name: "Item", PriceCents: dto.Cents(int64(i * 100)), Currency: "EUR", Status: "active"}
if _, err := c.Create(ctx, fmt.Sprintf("key-%d", i), in); err != nil {
t.Fatal(err)
}
}
// A retry with the same key does not create a sixth product.
if _, err := c.Create(ctx, "key-0", dto.ProductWrite{SKU: "SKU-0", Name: "Item", PriceCents: dto.Cents(0), Currency: "EUR", Status: "active"}); err != nil {
t.Fatal(err)
}
var n int
for p, err := range c.All(ctx, url.Values{"limit": {"2"}, "sort": {"price"}}) {
if err != nil {
t.Fatal(err)
}
if p.PriceCents != int64(n*100) {
t.Fatalf("item %d has price %d", n, p.PriceCents)
}
n++
}
if n != 5 {
t.Fatalf("iterated %d products, want 5", n)
}
var apiErr *client.Error
_, err := c.Create(ctx, "key-x", dto.ProductWrite{SKU: "x"})
if !errors.As(err, &apiErr) || apiErr.Problem.Status != http.StatusUnprocessableEntity {
t.Fatalf("want a 422 problem, got %v", err)
}
stop() // like SIGTERM
select {
case err := <-done:
if err != nil {
t.Fatalf("graceful shutdown returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("did not shut down")
}
}
func TestRunRejectsBadConfig(t *testing.T) {
err := app.Run(t.Context(), []string{"api"}, func(string) string { return "" }, io.Discard)
if err == nil {
t.Fatal("want a config error without API_CURSOR_KEY")
}
}پیکربندی از محیط (Configuration via env) مهم
به زبان ساده: هر چیزی که بین لپتاپ، Staging و Production عوض میشود، از Listen address و Timeout تا Secret و Limit، از متغیر محیطی (Environment variable) میآید. یکبار هنگام Startup در Config تایپدار خوانده و اعتبارسنجی میشود و مثل هر وابستگی دیگری به پایین میرود.
بدفهمی رایج: «هرجا مقدار لازم شد os.Getenv بخوان.» خواندن پراکنده جلوی Validation کامل Startup را میگیرد؛ خرابی تازه با اولین درخواست آشکار میشود، فهرست تنظیمات یک جا نیست و تستهای t.Setenv موازی نمیشوند. Twelve-factor میگوید "Store config in the environment"، اما "how code modules are connected" را Config نمیداند؛ Wiring در Composition root میماند.
تعریف: config.Load(getenv func(string) string) (Config, error) پیشفرضها را اعمال و با time.ParseDuration، strconv.ParseInt و slog.Level.UnmarshalText مقدارها را تبدیل میکند. بازه و Secret ضروری را بررسی و خطاها را با errors.Join از Go 1.20 جمع میکند تا یک Deploy ناموفق همهٔ ایرادها را نشان دهد. Flagهای args با flag.NewFlagSet میتوانند برای اجرای محلی Env را Override کنند.
1 API_ADDR=:8080 API_SHUTDOWN_TIMEOUT=soon API_LOG_LEVEL=loud ./api
2 config.Load -> errors.Join(
API_SHUTDOWN_TIMEOUT="soon": want a positive duration like 10s,
API_CURSOR_KEY: required, at least 16 bytes (signs page tokens),
API_LOG_LEVEL="loud": ...)
3 Run returns "config: ..." -> main prints it, exit 1 -> the orchestrator keeps the old versionسناریوی واقعی: Deployment در Kubernetes مقدار را از ConfigMap و Secret میگیرد؛ کلید امضا پیش از رسیدن ترافیک بررسی میشود؛ Staging سقف بدنهٔ 10 KiB دارد تا 413 تست شود؛ اجرای محلی از -addr 127.0.0.1:8088 استفاده میکند.
| متغیر | پیشفرض | معنا |
|---|---|---|
API_ADDR | :8080 | Listen address؛ Flag -addr مقدم است |
API_SHUTDOWN_TIMEOUT | 10s | مهلت Server.Shutdown |
API_DRAIN_DELAY | 0s | فاصلهٔ خراب شدن /readyz تا بستن Listener |
API_MAX_BODY_BYTES | 1048576 | سقف MaxBytesReader؛ بالاتر 413 |
API_CURSOR_KEY | اجباری، 16+ بایت | مادهٔ کلید رمز Page token؛ کلید AES-256-GCM برابر SHA-256 آن است |
API_LOG_LEVEL | INFO | سطح slog |
API_REQUIRE_IDEMPOTENCY_KEY | false | پاسخ 400 برای POST بدون کلید |
راهحل / نحوهٔ استفاده: کتابخانهها Struct را از Tag پر میکنند. caarlos0/env میگوید "parse environment variables into structs" با Tagهایی مثل env:"HOME"؛ kelseyhightower/envconfig نامهای "alternate, default, and required" دارد. Loader دستی این فصل آنقدر کوتاه است که وابستگی لازم نیست. تنظیم عمومی Flag، Env و slog در CLI Flags, Environment Variables & Logging است.
// Package config reads the service configuration from the environment
// (twelve-factor style) through an injected getenv, so tests never touch the
// real process environment.
package config
import (
"errors"
"fmt"
"log/slog"
"strconv"
"time"
)
// Config is everything the binary needs to start. No package-level state.
type Config struct {
Addr string
ShutdownTimeout time.Duration
DrainDelay time.Duration
MaxBodyBytes int64
CursorKey []byte
LogLevel slog.Level
RequireIdemKey bool
}
// Load validates every variable and reports all problems at once.
func Load(getenv func(string) string) (Config, error) {
c := Config{Addr: ":8080", ShutdownTimeout: 10 * time.Second, MaxBodyBytes: 1 << 20}
var errs []error
if v := getenv("API_ADDR"); v != "" {
c.Addr = v
}
if v := getenv("API_SHUTDOWN_TIMEOUT"); v != "" {
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
errs = append(errs, fmt.Errorf("API_SHUTDOWN_TIMEOUT=%q: want a positive duration like 10s", v))
}
c.ShutdownTimeout = d
}
if v := getenv("API_DRAIN_DELAY"); v != "" {
d, err := time.ParseDuration(v)
if err != nil || d < 0 {
errs = append(errs, fmt.Errorf("API_DRAIN_DELAY=%q: want a duration like 5s", v))
}
c.DrainDelay = d
}
if v := getenv("API_MAX_BODY_BYTES"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n <= 0 {
errs = append(errs, fmt.Errorf("API_MAX_BODY_BYTES=%q: want a positive integer", v))
}
c.MaxBodyBytes = n
}
key := getenv("API_CURSOR_KEY")
if len(key) < 16 {
errs = append(errs, errors.New("API_CURSOR_KEY: required, at least 16 bytes (signs page tokens)"))
}
c.CursorKey = []byte(key)
if v := getenv("API_LOG_LEVEL"); v != "" {
if err := c.LogLevel.UnmarshalText([]byte(v)); err != nil {
errs = append(errs, fmt.Errorf("API_LOG_LEVEL=%q: %w", v, err))
}
}
c.RequireIdemKey = getenv("API_REQUIRE_IDEMPOTENCY_KEY") == "true"
return c, errors.Join(errs...)
}صفحهبندی: Offset در برابر Cursor/Keyset، Headerِ Link و next_cursor حیاتی
به زبان ساده: صفحهبندی (Pagination) هر بار بخشی از مجموعه را میدهد. Offset میگوید «40 مورد را رد کن، 20 مورد بگیر»؛ Keyset یا Cursor میگوید «20 مورد پس از آخرین مورد دیدهشده را بگیر». پاسخ next_cursor و Header Link با URL صفحهٔ بعد دارد؛ کلاینت تا نبودن لینک ادامه میدهد.
بدفهمی رایج: «چند هزار ردیف داریم، Offset کافی است.» مسئله فقط سرعت نیست. Insert در ابتدای نتایج بین دو درخواست، جای همهٔ ردیفها را عوض میکند و یکی دوباره دیده میشود؛ Delete باعث جاافتادن میشود. Markus Winand میگوید "the database must still fetch these rows from the disk and bring them in order before it can send the following ones" و "think about what happens if a new row is inserted between fetching two pages". Keyset هر دو مسئله را حل میکند، به قیمت نداشتن پرش مستقیم به صفحهٔ 37.
تعریف: Keyset ترتیب یکتای کامل میخواهد: ستون Sort بهاضافهٔ id بهعنوان رفع تساوی (Tie-breaker). شرط WHERE (price_cents, id) > ($1, $2) ORDER BY price_cents, id LIMIT n+1 با Index مرکب (price_cents, id) در هر صفحه یک Seek دارد. Cursor کلید آخرین ردیف را حمل میکند. قواعد AIP-158 در snippetها رعایت میشوند: page_size صفر یعنی پیشفرض مستند، مقدار بیش از سقف "should coerce down"، مقدار منفی خطاست و next_page_token خالی "the only way to communicate end-of-collection". Tokenها "must be opaque (but URL-safe) strings, and must not be user-parseable". همچنین "Base-64 encoding an otherwise-transparent page token is not a sufficient obfuscation mechanism." پس اینجا Token با AES-256-GCM و کلید مشتقشده از API_CURSOR_KEY رمز میشود؛ هر Token یک Nonce تصادفی دارد و با base64url نمایش داده میشود. کلاینت نه موقعیت را میخواند نه تغییر میدهد؛ GCM اصالت Ciphertext را کنترل میکند و تغییر یک بایت 400 میدهد. Tokenهای یک موقعیت هم متفاوتاند. Payload رمزشده Hash فیلتر و Sort را هم دارد؛ استفادهٔ Cursor با Query دیگر 400 است.
1 GET /v1/products?sort=price&limit=2
2 repo.List(limit+1=3) -> SKU-1(100) SKU-2(200) SKU-3(300) 3 > 2: more exist
3 page = first 2; cursor = AES-GCM(nonce, {q: hash("sort=price"), k: {p:200, i:<id of SKU-2>}})
4 200 {"data":[SKU-1,SKU-2],"next_cursor":"KBODNt5Z...","has_more":true}
Link: </v1/products?cursor=KBODNt5Z...&limit=2&sort=price>; rel="next"
5 GET that link -> decrypt -> WHERE (price_cents, id) > (200, '<id of SKU-2>') -> SKU-3, SKU-4
6 same cursor with sort=name -> 400 invalid-query (token bound to its query)سناریوی واقعی: تکرار محصول در Infinite scroll جلوی چشم کاربر است؛ Export شبانه با OFFSET 900000 برای هر صفحه چند ثانیه میسوزاند؛ شریک تجاری «همهچیز پس از Cursor قبلی» را Sync میکند؛ جدول مدیریتی واقعاً شمارهٔ صفحه و Total میخواهد که Offset محدود برای آن قابل قبول است.
| API | درخواست | پاسخ | روش |
|---|---|---|---|
| این فصل | limit، cursor | data، next_cursor، has_more، Link: rel="next" | Keyset با Token مبهم و رمزشده |
| Stripe | limit از 1 تا 100، پیشفرض 10؛ starting_after، ending_before | has_more | Cursor بر پایهٔ Object ID |
| Google AIP-158 | page_size، page_token | next_page_token و total_size اختیاری | Opaque token |
| GitHub REST | per_page با سقف معمول 100 و کاهش مقدار اضافی، page، before/after یا since | Header link با rel="next" | Offset یا Cursor بسته به Endpoint |
| JSON:API cursor profile | page[size]، page[after]، page[before] | Links و Meta | Cursor |
Laravel paginate / simplePaginate / cursorPaginate | ?page= / ?cursor= | links، meta در API Resources | Offset / Offset / Keyset |
Offset، LIMIT/OFFSET | Keyset یا Cursor | |
|---|---|---|
| هزینهٔ صفحهٔ N | با N رشد میکند؛ خواندن و دور ریختن | ثابت؛ Index seek |
| Insert/Delete بین صفحهها | تکرار یا جاافتادگی | پایدار |
| پرش به صفحهٔ 37 | بله | نه |
| شمارش کل (Total count) | طبیعی؛ COUNT(*) اغلب کند است | جدا و اختیاری |
| Sort ستون غیر یکتا | کار میکند، تساوی ناپایدار | به Tie-breaker با id نیاز دارد |
| امکان خواندن یا دستکاری کلاینت | بله؛ هر Offset دلخواه | با Token رمزشده و احرازشده نه |
راهحل / نحوهٔ استفاده: بستهٔ زیر Limit را محدود و Token را رمز میکند. SQL در pgrepo.BuildList و سازوکار است؛ طراحی Index در Pagination.
// Package pagination turns a keyset position into an opaque, encrypted and
// authenticated page token and back.
package pagination
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"academy/rest-api-project/product"
)
const (
DefaultLimit = 20
MaxLimit = 100
)
// ErrBadCursor covers every reason a token is rejected: garbled, forged, or
// minted for a different filter/sort than the current request.
var ErrBadCursor = errors.New("invalid cursor")
// Codec encrypts tokens with AES-256-GCM under a key derived from Key, with a
// random nonce per token. Clients can neither read the position (AIP-158:
// tokens "must not be user-parseable"; base64 of JSON is not enough) nor
// forge or edit one (GCM authenticates it).
type Codec struct {
Key []byte
}
type token struct {
Q string `json:"q"` // hash of filter + sort
C product.Cursor `json:"k"`
}
func (c Codec) aead() cipher.AEAD {
k := sha256.Sum256(c.Key)
block, _ := aes.NewCipher(k[:]) // a 32-byte key never fails
g, _ := cipher.NewGCM(block)
return g
}
// Encode returns base64url(nonce || ciphertext).
func (c Codec) Encode(query string, cur product.Cursor) string {
body, _ := json.Marshal(token{Q: queryHash(query), C: cur})
g := c.aead()
nonce := make([]byte, g.NonceSize())
_, _ = rand.Read(nonce)
return base64.RawURLEncoding.EncodeToString(g.Seal(nonce, nonce, body, nil))
}
// Decode authenticates and decrypts the token and checks it belongs to query.
func (c Codec) Decode(query, s string) (product.Cursor, error) {
raw, err := base64.RawURLEncoding.DecodeString(s)
g := c.aead()
if err != nil || len(raw) < g.NonceSize() {
return product.Cursor{}, ErrBadCursor
}
body, err := g.Open(nil, raw[:g.NonceSize()], raw[g.NonceSize():], nil)
if err != nil {
return product.Cursor{}, ErrBadCursor
}
var t token
if err := json.Unmarshal(body, &t); err != nil || t.Q != queryHash(query) {
return product.Cursor{}, ErrBadCursor
}
return t.C, nil
}
func queryHash(q string) string {
sum := sha256.Sum256([]byte(q))
return base64.RawURLEncoding.EncodeToString(sum[:6])
}
// ClampLimit applies the AIP-158 rules: 0 means the default, anything above
// the maximum is coerced down, negatives are an error for the caller.
func ClampLimit(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n == 0:
return DefaultLimit, true
case n > MaxLimit:
return MaxLimit, true
}
return n, true
}package pagination
import (
"encoding/base64"
"errors"
"slices"
"strings"
"testing"
"academy/rest-api-project/product"
)
func TestRoundTripAndTamper(t *testing.T) {
c := Codec{Key: []byte("test-key")}
cur := product.Cursor{PriceCents: 1999, ID: "prd_42"}
tok := c.Encode("sort=price", cur)
got, err := c.Decode("sort=price", tok)
if err != nil || got != cur {
t.Fatalf("round trip: %+v %v", got, err)
}
if _, err := c.Decode("sort=name", tok); !errors.Is(err, ErrBadCursor) {
t.Fatalf("token reused with another sort must fail, got %v", err)
}
forged := "x" + tok[1:]
if _, err := c.Decode("sort=price", forged); !errors.Is(err, ErrBadCursor) {
t.Fatalf("edited token must fail, got %v", err)
}
}
func TestClampLimit(t *testing.T) {
for in, want := range map[int]int{0: DefaultLimit, 7: 7, 500: MaxLimit} {
if got, ok := ClampLimit(in); !ok || got != want {
t.Errorf("ClampLimit(%d) = %d, %v", in, got, ok)
}
}
if _, ok := ClampLimit(-1); ok {
t.Error("negative limit must be rejected")
}
}
// TestOffsetDriftVsKeyset shows why the API pages by keyset: a row inserted
// at the head between two requests duplicates a row under OFFSET and is
// harmless under "WHERE id < last_seen".
func TestOffsetDriftVsKeyset(t *testing.T) {
rows := []int{9, 8, 7, 6, 5, 4} // newest first, like ORDER BY id DESC
offsetPage := func(rows []int, offset, limit int) []int { return rows[offset : offset+limit] }
keysetPage := func(rows []int, after, limit int) []int {
var out []int
for _, r := range rows {
if r < after && len(out) < limit {
out = append(out, r)
}
}
return out
}
p1 := offsetPage(rows, 0, 3) // 9 8 7
k1 := keysetPage(rows, 1<<31, 3)
rows = append([]int{10}, rows...) // a new row arrives
p2 := offsetPage(rows, 3, 3) // 7 6 5: 7 again
k2 := keysetPage(rows, k1[len(k1)-1], 3) // 6 5 4
if !slices.Contains(p1, p2[0]) {
t.Fatalf("expected offset drift, got %v then %v", p1, p2)
}
if !slices.Equal(k2, []int{6, 5, 4}) {
t.Fatalf("keyset page 2 = %v", k2)
}
}
// AIP-158: tokens must not be user-parseable; base64 of JSON is not enough.
func TestTokenIsOpaque(t *testing.T) {
c := Codec{Key: []byte("test-key-test-key")}
cur := product.Cursor{PriceCents: 1999, ID: "prd_42"}
a, b := c.Encode("sort=price", cur), c.Encode("sort=price", cur)
if a == b {
t.Fatal("two tokens for the same position must differ (random nonce)")
}
for _, part := range strings.Split(a, ".") {
raw, _ := base64.RawURLEncoding.DecodeString(part)
if strings.Contains(string(raw), "prd_42") || strings.Contains(string(raw), "1999") {
t.Fatalf("token reveals the position: %q", raw)
}
}
if got, err := c.Decode("sort=price", b); err != nil || got != cur {
t.Fatalf("round trip: %+v %v", got, err)
}
}فیلتر کردن و مرتبسازی (Filtering and sorting) مهم
به زبان ساده: فیلتر کردن (Filtering) مجموعه را محدود میکند، مثل ?status=active&min_price=500. مرتبسازی (Sorting) ترتیب میدهد؛ مثلاً ?sort=-price نزولی است. هر دو Query parameter هستند، با Allow-list بررسی میشوند و اعتبار Cursor به هر دو وابسته است.
بدفهمی رایج: «پارامتر Sort را مستقیم در ORDER BY بگذار.» این تزریق SQL (SQL injection) است، مثل ?sort=name;DROP TABLE products. همچنین اجازهٔ Sort روی ستون بدون Index یک درخواست را به Full table scan تبدیل میکند. اشتباه دیگر پذیرفتن زبان فیلتر آزاد بدون بودجهٔ اجراست؛ AIP-160 دستور زبان Filter دارد ولی هشدار میدهد نیازها "evolve frequently".
تعریف: هر Filter نام و نوع دارد: status باید شناختهشده و Price عدد صحیح غیرمنفی برحسب سنت باشد. sort از فهرست مجاز با پیشوند اختیاری - میآید؛ Map ثابت sortColumns در pgrepo آن را به ستون تبدیل میکند و همیشه id را برای Tie-breaker اضافه میکند. هر Sort مجاز Index روی (column, id) دارد. اینجا پارامتر ناشناخته نادیده گرفته میشود؛ API سختگیر میتواند 400 بدهد.
1 ?status=active&min_price=500&sort=-price&limit=20
2 parseList: status ok · min_price=500 · sort -> (SortPrice, desc) · limit 20
3 fingerprint = "max_price=&min_price=500&sort=-price&status=active" cursor binds to it
4 SQL: WHERE status = $1 AND price_cents >= $2 ORDER BY price_cents DESC, id DESC LIMIT $3
5 ?sort=colour -> 400 "sort: must be one of created_at, price, name, optionally prefixed with -"سناریوی واقعی: فروشگاه با دسته و بازهٔ قیمت فیلتر میشود؛ مدیریت Status را با آخرین تغییر مرتب میکند؛ کلاینت گزارش نباید ستون متن بدون Index را Sort کند؛ شریک برای Sync شرط updated_at > X میخواهد.
| سبک | مثال | مزیت | هزینه |
|---|---|---|---|
| پارامتر نامدار، این فصل | ?status=active&min_price=500 | تایپدار، مستند در OpenAPI، Index ساده | یک پارامتر برای هر Filter |
| عملگر براکتی | ?price[gte]=500 | عملگرهای زیاد | مستندسازی و Validation سختتر |
| عبارت Filter در AIP-160 | filter=status = "ACTIVE" AND price > 500 | قدرت بیان | Parser و کنترل هزینه |
خانوادهٔ filter[...] در JSON:API | ?filter[status]=active | خانوادهٔ تعریفشده در Spec | معنا با سرور است |
| Sort | ?sort=-price,name | آشنا؛ JSON:API هم - را نزولی میداند | هر ترکیب Index میخواهد |
راهحل / نحوهٔ استفاده: تمام Parser در parseList فایل handlers.go است. تست TestUnknownSortFallsBackToAllowList محدود بودن SQL builder به Allow-list را ثابت میکند.
package pgrepo
import (
"errors"
"fmt"
"slices"
"testing"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
var _ service.Repository = (*Repo)(nil)
func TestBuildListKeysetDesc(t *testing.T) {
minPrice := int64(500)
q := product.ListQuery{
Status: product.StatusActive, MinPrice: &minPrice,
Sort: product.SortPrice, Desc: true, Limit: 20,
After: &product.Cursor{PriceCents: 1999, ID: "prd_42"},
}
sql, args := BuildList(q)
want := "SELECT " + columns + " FROM products WHERE status = $1 AND price_cents >= $2" +
" AND (price_cents, id) < ($3, $4) ORDER BY price_cents DESC, id DESC LIMIT $5"
if sql != want {
t.Fatalf("sql:\n%s\nwant:\n%s", sql, want)
}
if !slices.Equal(args, []any{"active", int64(500), int64(1999), "prd_42", 21}) {
t.Fatalf("args %v", args)
}
}
func TestUnknownSortFallsBackToAllowList(t *testing.T) {
sql, _ := BuildList(product.ListQuery{Sort: "name; DROP TABLE products", Limit: 1})
want := "SELECT " + columns + " FROM products ORDER BY created_at ASC, id ASC LIMIT $1"
if sql != want {
t.Fatalf("got %s", sql)
}
}
type pgErr string
func (e pgErr) Error() string { return "pg: " + string(e) }
func (e pgErr) SQLState() string { return string(e) }
func TestMapUniqueViolation(t *testing.T) {
err := fmt.Errorf("insert: %w", pgErr("23505"))
if !errors.Is(mapErr(err), product.ErrSKUTaken) {
t.Fatal("23505 must map to ErrSKUTaken")
}
if errors.Is(mapErr(pgErr("23503")), product.ErrSKUTaken) {
t.Fatal("other states pass through")
}
}تغییر جزئی: PATCH و JSON Merge Patch حیاتی
به زبان ساده: PUT کل بازنمایی قابل نوشتن (Writable representation) را میفرستد؛ PATCH فقط تغییرات را. در JSON Merge Patch با Content-Type: application/merge-patch+json، شکل Patch مثل سند است: عضو موجود مقدار میگیرد، عضو با null حذف میشود و عضو غایب دستنخورده میماند.
بدفهمی رایج: «بدنه را در همان Struct بخوان و فیلدهای غیرصفر را کپی کن.» آن وقت قیمت 0، فهرست خالی یا حذف فیلد اختیاری بیان نمیشود؛ غیبت، null و Zero value یکسان به نظر میرسند. Pointer برای Scalar کمک میکند، اما برای Object تودرتو کافی نیست. اعمال RFC 7396 روی JSON و سپس Decode و Validation مثل PUT این سوراخها را ندارد.
تعریف: RFC 5789، PATCH را اعمال "a set of changes described in the request entity" میداند؛ بهتعریف Idempotent نیست. الگوریتم RFC 7396: اگر Patch یک Object نیست جای Target را میگیرد؛ وگرنه هر عضو null عضو متناظر را حذف و هر مقدار دیگر بازگشتی Merge میشود. Array جایگزین میشود، نه Merge. قالب "is not appropriate for all JSON syntaxes": نمیتوانید مقدار واقعی null بگذارید یا یک عضو Array را تغییر دهید. برای آن JSON Patch در RFC 6902 با application/json-patch+json و عملیات add، remove، replace، move، copy و test مناسب است. snippet همهٔ پانزده Test case پیوست A در RFC 7396 را پاس میکند.
1 stored {"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"draft","tags":["kitchen"]}
2 PATCH If-Match: "v1" {"price_cents":1200,"status":"active","tags":null}
3 merged {"sku":"MUG-1","name":"Mug","price_cents":1200,"currency":"EUR","status":"active"}
4 decode DisallowUnknownFields into ProductWrite; Valid(ctx) -> ok
5 svc.Replace version 1 -> 2; 200, ETag "v2", "tags": []
6 PATCH {"id":"prd_999"} -> merged doc has unknown member "id" -> 400 (read-only fields cannot be patched)سناریوی واقعی: موبایل یک فیلد پروفایل بزرگ را ویرایش میکند؛ مدیر تخفیف اختیاری را پاک میکند؛ Sync فقط فیلد تغییرکرده میفرستد؛ در صفحهٔ تنظیمات یک گزینه از Object تودرتوی notifications عوض میشود.
| روش | Media type | مقدار واقعی null | تغییر یک عضو Array | Idempotent | پیچیدگی |
|---|---|---|---|---|---|
PUT با Representation کامل | application/json | بله | با ارسال کل Array | بله | کمترین |
| JSON Merge Patch، RFC 7396 | application/merge-patch+json | نه؛ null یعنی حذف | نه؛ Array جایگزین میشود | در عمل برای Patch یکسان بله | کم |
| JSON Patch، RFC 6902 | application/json-patch+json | بله | بله | در حالت کلی نه؛ مثل add به Array | متوسط |
| Struct با Pointer field | application/json | نه | نه | بستگی دارد | با هر فیلد بیشتر میشود |
Field mask، update_mask در AIP-134 | gRPC/JSON | بله | بله | بله | متوسط |
راهحل / نحوهٔ استفاده: evanphx/json-patch هر دو RFC 7396 و RFC 6902 را پیاده میکند. پیادهسازی چهلخطی زیر برای Merge patch کافی است و با جدول خود RFC تست میشود.
// Package mergepatch implements RFC 7396 JSON Merge Patch on decoded JSON
// values (map[string]any, []any, string, float64, bool, nil).
package mergepatch
import (
"encoding/json"
"fmt"
)
// MediaType is the content type a PATCH request must declare.
const MediaType = "application/merge-patch+json"
// Apply is the algorithm of RFC 7396 section 2, line for line: a non-object
// patch replaces the target; an object patch is merged member by member, and
// a null member deletes that member from the target.
func Apply(target, patch any) any {
p, ok := patch.(map[string]any)
if !ok {
return patch
}
t, ok := target.(map[string]any)
if !ok {
t = map[string]any{}
}
for name, value := range p {
if value == nil {
delete(t, name)
continue
}
t[name] = Apply(t[name], value)
}
return t
}
// ApplyJSON patches a JSON document and returns the new document.
func ApplyJSON(doc, patch []byte) ([]byte, error) {
var t, p any
if err := json.Unmarshal(doc, &t); err != nil {
return nil, fmt.Errorf("target: %w", err)
}
if err := json.Unmarshal(patch, &p); err != nil {
return nil, fmt.Errorf("patch: %w", err)
}
return json.Marshal(Apply(t, p))
}package mergepatch
import (
"encoding/json"
"reflect"
"testing"
)
// The example test cases of RFC 7396 Appendix A, verbatim.
var appendixA = []struct{ original, patch, result string }{
{`{"a":"b"}`, `{"a":"c"}`, `{"a":"c"}`},
{`{"a":"b"}`, `{"b":"c"}`, `{"a":"b","b":"c"}`},
{`{"a":"b"}`, `{"a":null}`, `{}`},
{`{"a":"b","b":"c"}`, `{"a":null}`, `{"b":"c"}`},
{`{"a":["b"]}`, `{"a":"c"}`, `{"a":"c"}`},
{`{"a":"c"}`, `{"a":["b"]}`, `{"a":["b"]}`},
{`{"a":{"b":"c"}}`, `{"a":{"b":"d","c":null}}`, `{"a":{"b":"d"}}`},
{`{"a":[{"b":"c"}]}`, `{"a":[1]}`, `{"a":[1]}`},
{`["a","b"]`, `["c","d"]`, `["c","d"]`},
{`{"a":"b"}`, `["c"]`, `["c"]`},
{`{"a":"foo"}`, `null`, `null`},
{`{"a":"foo"}`, `"bar"`, `"bar"`},
{`{"e":null}`, `{"a":1}`, `{"e":null,"a":1}`},
{`[1,2]`, `{"a":"b","c":null}`, `{"a":"b"}`},
{`{}`, `{"a":{"bb":{"ccc":null}}}`, `{"a":{"bb":{}}}`},
}
func TestRFC7396AppendixA(t *testing.T) {
for _, c := range appendixA {
got, err := ApplyJSON([]byte(c.original), []byte(c.patch))
if err != nil {
t.Fatal(err)
}
var g, w any
_ = json.Unmarshal(got, &g)
_ = json.Unmarshal([]byte(c.result), &w)
if !reflect.DeepEqual(g, w) {
t.Errorf("%s + %s = %s, want %s", c.original, c.patch, got, c.result)
}
}
}ETag و If-Match: همزمانی خوشبینانه روی HTTP حیاتی
به زبان ساده: هر Read یک ETag میدهد؛ اینجا "v3" یعنی نسخهٔ Aggregate. کلاینت هنگام تغییر همان را در If-Match پس میفرستد. اگر دیگری در این فاصله نوشته باشد، سرور بهجای پاک کردن ویرایش او 412 میدهد. این همزمانی خوشبینانه (Optimistic concurrency) است.
بدفهمی رایج: «DB ما Transaction دارد، پس ویرایش همزمان امن است.» Transaction یک درخواست را پوشش میدهد؛ گم شدن بهروزرسانی (Lost update) میان خواندن و نوشتن دو نفر، با چند دقیقه فاصله رخ میدهد. فقط شرط نسخه هنگام نوشتن جلوی آن را میگیرد. «ETag فقط برای Cache است» هم درست نیست: If-None-Match برای Cache و 304 است؛ If-Match برای Write ایمن.
تعریف: RFC 9110 دربارهٔ If-Match میگوید سرور "MUST NOT perform the requested method if the condition evaluates to false" و میتواند 412 Precondition Failed بدهد. مقایسهٔ قوی (Strong comparison) استفاده میشود، پس Tag ضعیف W/"..." هرگز Match نیست. RFC 6585 کد 428 Precondition Required را با هدف "Its typical use is to avoid the "lost update" problem" اضافه میکند. در این فصل PUT، PATCH و DELETE به If-Match نیاز دارند؛ * یعنی هر نسخهٔ فعلی. هر Tag فهرست با Tag فعلی مثل "v2" عیناً مقایسه میشود؛ عدد از ورودی کلاینت استخراج نمیشود، پس "v02" و "v-1" Match نیستند. GET با If-None-Match از مقایسهٔ ضعیف استفاده میکند: "A recipient MUST use the weak comparison function when comparing entity tags for If-None-Match"؛ پس W/"v2" و *، 304 میدهند. بررسی نسخه دوباره داخل همان UPDATE ... WHERE version = $9 انجام میشود تا دو درخواست عبورکرده از Handler هم نتوانند با هم برنده شوند. AIP-154 همین سازوکار را با فیلد etag برای gRPC بیان میکند.
client A API client B
1 GET -> ETag "v1" GET -> ETag "v1"
2 PATCH If-Match "v1" {price} ─▶ version 1 == 1 -> v2
3 ◀─ 200 ETag "v2"
4 version 2 != 1 ◀─────────── PATCH If-Match "v1" {name}
5 412 problem stale-version ─▶ re-GET v2, re-apply, retry
6 PUT without If-Match ─▶ 428 if-match-requiredسناریوی واقعی: دو پشتیبان یک مشتری را ویرایش میکنند؛ قیمت مدیر با Bulk import رقابت میکند؛ موبایل پس از یک ساعت Offline تغییر قدیمی را Sync میکند؛ دو ویراستار یک صفحهٔ CMS را منتشر میکنند.
| سازوکار | جای نسخه | پاسخ تعارض | نکته |
|---|---|---|---|
ETag + If-Match، این فصل | Header، از ستون version | 412؛ نبودن Header برابر 428 | با هر HTTP client و Cache کار میکند |
| Version در Body | JSON مثل "version": 3 | 409 یا 412 | ساده برای کلاینت، نامرئی برای ابزار HTTP |
| Google AIP-154 | فیلد etag در Resource | ABORTED؛ در 2021 جای FAILED_PRECONDITION آمد | APIهای gRPC-first |
| آخرین نویسنده برنده (Last write wins) | هیچجا | ندارد | فقط برای دادهٔ تکنویسنده |
قفل بدبینانه، SELECT ... FOR UPDATE | DB، در یک درخواست | انتظار | دو درخواست HTTP را پوشش نمیدهد |
راهحل / نحوهٔ استفاده: Parserِ If-Match پایین است؛ سمت DB ستون نسخه را در Optimistic vs Pessimistic Locking بخوانید.
package httpapi
import (
"net/http"
"strconv"
"strings"
"academy/rest-api-project/problem"
)
// etag derives a strong entity tag from the aggregate version. Clients treat
// it as opaque; the server only ever compares it as a string.
func etag(version int64) string { return `"v` + strconv.FormatInt(version, 10) + `"` }
// condition is a parsed If-Match or If-None-Match field: "*" or a list of
// entity-tags, kept literally (W/ prefix included).
type condition struct {
any bool
tags []string
}
// parseCondition splits a field value into entity-tags (RFC 9110 8.8.3).
// Anything that is not a well-formed tag is kept as-is and never matches.
func parseCondition(h string) condition {
h = strings.TrimSpace(h)
if h == "*" {
return condition{any: true}
}
var c condition
for len(h) > 0 {
h = strings.TrimLeft(h, " \t,")
if h == "" {
break
}
start := 0
if strings.HasPrefix(h, "W/") {
start = 2
}
if len(h) > start && h[start] == '"' {
if end := strings.IndexByte(h[start+1:], '"'); end >= 0 {
n := start + 1 + end + 1
c.tags = append(c.tags, h[:n])
h = h[n:]
continue
}
}
junk, rest, _ := strings.Cut(h, ",") // malformed member
c.tags = append(c.tags, strings.TrimSpace(junk))
h = rest
}
return c
}
// strongMatch is the If-Match test: both tags strong and identical.
func (c condition) strongMatch(current string) bool {
if c.any {
return true
}
for _, t := range c.tags {
if !strings.HasPrefix(t, "W/") && t == current {
return true
}
}
return false
}
// weakMatch is the If-None-Match test: opaque parts equal, W/ ignored.
func (c condition) weakMatch(current string) bool {
if c.any {
return true
}
cur := strings.TrimPrefix(current, "W/")
for _, t := range c.tags {
if strings.TrimPrefix(t, "W/") == cur {
return true
}
}
return false
}
// requireIfMatch makes PUT, PATCH and DELETE conditional: no header is 428
// Precondition Required (RFC 6585). Matching happens later, against the
// current representation's tag.
func requireIfMatch(r *http.Request) (condition, *problem.Problem) {
h := strings.TrimSpace(r.Header.Get("If-Match"))
if h == "" {
return condition{}, problem.New(http.StatusPreconditionRequired, "if-match-required", "If-Match header is required",
"send the ETag from your last GET to avoid overwriting someone else's change")
}
return parseCondition(h), nil
}
func staleProblem() *problem.Problem {
return problem.New(http.StatusPreconditionFailed, "stale-version", "Resource changed since you read it",
"GET it again and retry with the new ETag in If-Match")
}کلید Idempotency برای POST حیاتی
به زبان ساده: POST هر بار چیز تازهای میسازد. اگر پاسخ در شبکه گم شود، کلاینت نمیداند محصول یا پرداخت ساخته شده یا نه. کلید تکرار ایمن (Idempotency key) در Header Idempotency-Key با هر Retry ثابت میماند؛ سرور پاسخ نخست را برمیگرداند، نه اینکه دوباره کار کند.
بدفهمی رایج: «Unique constraint کافی است.» ردیف تکراری را میگیرد اما Retry بیخطر را به 409 تبدیل میکند؛ برای پرداخت یا ایمیل بدون Natural key هم چنین قیدی ندارید. صرف ذخیرهٔ کلید و رد تکرار هم کافی نیست: پاسخ باید ذخیره و بازپخش شود، استفادهٔ همان کلید با بدنهٔ دیگر تشخیص داده شود و Retry هنگام اجرای درخواست اول مدیریت شود.
تعریف: پیشنویس IETF میگوید کلید "MUST be unique and MUST NOT be reused with another request with a different request payload" و سرور "MAY compute a fingerprint of the request payload". کلید اجباریِ غایب 400، کلید با Payload متفاوت 422 و Retry "while the original request is still being processed" برابر 409 است. Stripe میگوید "Stripe saves the status code and body of the first request made with a given idempotency key" و "you can remove keys from the system automatically after they’re at least 24 hours old". کلیدها "up to 255 characters long" هستند و "Don’t send idempotency keys in GET and DELETE requests because it has no effect". snippet کلید را به Method و Path محدود میکند. چون پیش از MaxBytesReader خود Handler باید Body را برای اثر انگشت (Fingerprint) بخواند، خودش سقف بدنه را اعمال میکند. Fingerprint برابر SHA-256 بدنه است. در Panic کلید آزاد میشود تا Retry تا TTL در 409 نماند. Buffer با Headerهای بیرونی شروع میشود تا Problem، request_id را حفظ کند. فقط پاسخ نهایی غیر 5xx ذخیره میشود؛ Stripe v1 حتی 500 را بازپخش میکند و این انتخاب طراحی است. Header اختصاصی Idempotent-Replayed: true بازپخش را مشخص میکند.
1 POST Idempotency-Key "8e03..." body B -> new: reserve (in flight) -> handler -> 201 -> store
2 POST same key, same B (retry) -> done: replay 201, same Location, Idempotent-Replayed: true
3 POST same key while 1 still runs -> in flight: 409 idempotency-key-in-flight
4 POST same key, body B' -> fingerprint differs: 422 idempotency-key-reused
5 first attempt answered 503 -> not stored; the retry runs the handler again
6 24 h later -> expired; the key is new againسناریوی واقعی: کاربر Checkout را دوبار میزند؛ موبایل با شبکهٔ ناپایدار پس از Timeout تکرار میکند؛ Webhook consumer دوباره تحویل میدهد؛ Job runner Batch نیمهکارهٔ ساخت را از نو آغاز میکند.
| تصمیم | این فصل | Stripe API v1 | پیشنویس IETF |
|---|---|---|---|
| Header | Idempotency-Key با یا بدون Quote | Idempotency-Key | Idempotency-Key، رشتهٔ Structured Field |
| اثر انگشت (Fingerprint) | SHA-256 بدنه | مقایسهٔ پارامترها | اختیاری؛ مستند شود |
| کلید با Payload دیگر | 422 | خطا | 422 |
| Retry همزمان | 409 | خطا؛ ذخیره نمیشود | 409 |
| ذخیرهٔ 5xx | نه | بله | تعیین نشده |
| زمان نگهداری (Retention) | 24 h، NewStore(ttl) | دستکم 24 h | تعیین نشده |
| محل ذخیره | حافظه، یک Instance | زیرساخت خودشان | تعیین نشده |
راهحل / نحوهٔ استفاده: با چند Instance، Store مشترک و رزرو اتمیک لازم است: جدول idempotency_keys با Primary key روی Scoped key و INSERT ... ON CONFLICT DO NOTHING، یا SET key value NX EX 86400 در Redis. اگر چند جدول تغییر میکنند، پاسخ ذخیرهشده و تغییر کسبوکار را در یک Transaction بنویسید. طراحی عمومی در API Idempotency است.
// Package idempotency makes POST safe to retry: the first response for an
// Idempotency-Key is stored and replayed for every retry with the same key
// and the same body (draft-ietf-httpapi-idempotency-key-header).
package idempotency
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"academy/rest-api-project/problem"
)
// Header is the request header name from the IETF draft (and Stripe).
const Header = "Idempotency-Key"
// ReplayedHeader marks a replayed response; the name is this API's choice.
const ReplayedHeader = "Idempotent-Replayed"
type record struct {
fingerprint string
done bool
status int
header http.Header
body []byte
at time.Time
}
// Store keeps records in memory. A multi-instance deployment needs a shared
// store (a table with a unique key, or Redis SET NX) with the same states.
type Store struct {
mu sync.Mutex
recs map[string]*record
ttl time.Duration
now func() time.Time
}
// NewStore keeps records for ttl (Stripe prunes keys after 24 hours).
func NewStore(ttl time.Duration, now func() time.Time) *Store {
return &Store{recs: map[string]*record{}, ttl: ttl, now: now}
}
// Middleware wraps POST handlers. required=true rejects a POST without a key.
// The body is read here (to fingerprint it), so the size limit applies here.
func (s *Store) Middleware(required bool, maxBytes int64) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := strings.Trim(r.Header.Get(Header), `"`) // the draft sends a quoted sf-string
if r.Method != http.MethodPost || key == "" {
if required && r.Method == http.MethodPost {
problem.Write(w, r, problem.New(http.StatusBadRequest, "idempotency-key-missing",
"Idempotency-Key header is required", "send a unique key (a UUID) per logical operation"))
return
}
next.ServeHTTP(w, r)
return
}
if maxBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
body, err := io.ReadAll(r.Body)
var tooBig *http.MaxBytesError
switch {
case errors.As(err, &tooBig):
problem.Write(w, r, problem.New(http.StatusRequestEntityTooLarge, "body-too-large", "Request body too large",
fmt.Sprintf("limit is %d bytes", tooBig.Limit)))
return
case err != nil:
problem.Write(w, r, problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", "could not read body"))
return
}
sum := sha256.Sum256(body)
fp := hex.EncodeToString(sum[:])
scope := r.Method + " " + r.URL.Path + " " + key
rec, fresh := s.begin(scope, fp)
switch {
case !fresh && rec.fingerprint != fp:
problem.Write(w, r, problem.New(http.StatusUnprocessableEntity, "idempotency-key-reused",
"Idempotency-Key reused with a different request body", ""))
return
case !fresh && !rec.done:
problem.Write(w, r, problem.New(http.StatusConflict, "idempotency-key-in-flight",
"A request with this Idempotency-Key is still being processed", "retry later"))
return
case !fresh:
replay(w, rec)
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
cw := &captureWriter{header: w.Header().Clone(), status: http.StatusOK} // keeps X-Request-ID
defer func() {
if v := recover(); v != nil {
s.abandon(scope) // a panic must not leave the key "in flight" until the TTL
panic(v)
}
}()
next.ServeHTTP(cw, r)
s.finish(scope, cw)
if rec, ok := w.(interface{ SetError(error) }); ok && cw.err != nil {
rec.SetError(cw.err) // pass the 5xx cause on to the access log
}
copyResponse(w, cw.header, cw.status, cw.buf.Bytes())
})
}
}
// begin returns the live record for scope, or reserves a new in-flight one.
func (s *Store) begin(scope, fp string) (rec record, fresh bool) {
s.mu.Lock()
defer s.mu.Unlock()
if r, ok := s.recs[scope]; ok && s.now().Sub(r.at) < s.ttl {
return *r, false
}
s.recs[scope] = &record{fingerprint: fp, at: s.now()}
return record{}, true
}
// finish stores a final response. 5xx are not stored, so the client may
// retry them (Stripe's v1 API stores even 500s; this is a design choice).
func (s *Store) finish(scope string, cw *captureWriter) {
s.mu.Lock()
defer s.mu.Unlock()
if cw.status >= 500 {
delete(s.recs, scope)
return
}
r := s.recs[scope]
h := cw.header.Clone()
h.Del("X-Request-ID") // a replay carries the retry's own request id header
r.done, r.status, r.header, r.body = true, cw.status, h, bytes.Clone(cw.buf.Bytes())
}
func (s *Store) abandon(scope string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.recs, scope)
}
func replay(w http.ResponseWriter, rec record) {
h := rec.header.Clone()
h.Set(ReplayedHeader, "true")
copyResponse(w, h, rec.status, rec.body)
}
func copyResponse(w http.ResponseWriter, h http.Header, status int, body []byte) {
for k, v := range h {
w.Header()[k] = v
}
w.WriteHeader(status)
_, _ = w.Write(body)
}
// captureWriter buffers the inner handler's response so it can be stored.
type captureWriter struct {
header http.Header
status int
wrote bool
buf bytes.Buffer
err error
}
// SetError keeps the internal cause that writeError attaches.
func (c *captureWriter) SetError(err error) { c.err = err }
func (c *captureWriter) Header() http.Header { return c.header }
func (c *captureWriter) WriteHeader(code int) {
if !c.wrote {
c.status, c.wrote = code, true
}
}
func (c *captureWriter) Write(p []byte) (int, error) {
c.wrote = true
return c.buf.Write(p)
}package idempotency
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func setup(handler http.HandlerFunc) (http.Handler, *atomic.Int32) {
var calls atomic.Int32
s := NewStore(24*time.Hour, time.Now)
h := s.Middleware(true, 1<<10)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
handler(w, r)
}))
return h, &calls
}
func post(h http.Handler, key, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/v1/products", strings.NewReader(body))
if key != "" {
req.Header.Set(Header, key)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestRetryIsReplayed(t *testing.T) {
h, calls := setup(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", "/v1/products/prd_1")
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, `{"id":"prd_1"}`)
})
first := post(h, `"8e03978e-40d5-43e8-bc93-6894a57f9324"`, `{"sku":"A"}`)
retry := post(h, `"8e03978e-40d5-43e8-bc93-6894a57f9324"`, `{"sku":"A"}`)
if first.Code != 201 || retry.Code != 201 || retry.Body.String() != first.Body.String() {
t.Fatalf("first %d %q, retry %d %q", first.Code, first.Body, retry.Code, retry.Body)
}
if retry.Header().Get(ReplayedHeader) != "true" || retry.Header().Get("Location") == "" {
t.Fatalf("replay headers %v", retry.Header())
}
if calls.Load() != 1 {
t.Fatalf("handler ran %d times, want 1", calls.Load())
}
}
func TestStatusCodesFromTheDraft(t *testing.T) {
started, release := make(chan struct{}), make(chan struct{})
h, _ := setup(func(w http.ResponseWriter, r *http.Request) {
close(started) // only the first request for k1 reaches the handler
<-release
w.WriteHeader(http.StatusCreated)
})
if got := post(h, "", `{}`).Code; got != http.StatusBadRequest {
t.Errorf("missing key: %d, want 400", got)
}
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); post(h, "k1", `{"sku":"A"}`) }()
<-started
if got := post(h, "k1", `{"sku":"A"}`).Code; got != http.StatusConflict {
t.Errorf("retry while the first is running: %d, want 409", got)
}
close(release)
wg.Wait()
if got := post(h, "k1", `{"sku":"B"}`).Code; got != http.StatusUnprocessableEntity {
t.Errorf("same key, other body: %d, want 422", got)
}
}
func TestServerErrorsAreNotStored(t *testing.T) {
fail := true
h, calls := setup(func(w http.ResponseWriter, r *http.Request) {
if fail {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusCreated)
})
if post(h, "k2", `{}`).Code != 503 {
t.Fatal("first attempt should fail")
}
fail = false
if got := post(h, "k2", `{}`).Code; got != 201 || calls.Load() != 2 {
t.Fatalf("retry after 5xx: %d, calls %d", got, calls.Load())
}
}
func TestBodyLimitAppliesBeforeFingerprinting(t *testing.T) {
h, calls := setup(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) })
if got := post(h, "big", strings.Repeat("x", 2<<10)).Code; got != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body: %d, want 413", got)
}
if calls.Load() != 0 {
t.Fatal("handler must not run")
}
}
func TestPanicReleasesTheKey(t *testing.T) {
boom := true
h, _ := setup(func(w http.ResponseWriter, r *http.Request) {
if boom {
panic("handler bug")
}
w.WriteHeader(http.StatusCreated)
})
func() {
defer func() { _ = recover() }()
post(h, "k3", `{}`)
}()
boom = false
if got := post(h, "k3", `{}`).Code; got != http.StatusCreated {
t.Fatalf("retry after a panic: %d, want 201 (not 409 in flight)", got)
}
}نسخهبندی با /v1 مهم
به زبان ساده: نسخهبندی (Versioning) در URL با /v1 شروع میشود. تغییر افزایشی مثل فیلد اختیاری یا Endpoint تازه در همان v1 میماند؛ تغییر ناسازگار مثل تغییر نام یا نوع فیلد و حذف Endpoint در /v2 میآید. دو نسخه تا مهاجرت کلاینتها کنار هم سرو میشوند.
بدفهمی رایج: «هر Release نسخهٔ API را بالا ببریم.» نسخه برای Breaking change است. AIP-185 میگوید APIها "must provide a major version number" و "Google APIs use v1, not v1.0, v1.1, or v1.4.2"؛ تغییر جزئی "updated in place" است. نبودن نسخه هم اولین تغییر ناسازگار را به مهاجرت همزمان همهٔ کلاینتها تبدیل میکند.
تعریف: Major version یک قرارداد ناسازگار را مشخص میکند. نسخه در مسیر (Path versioning) قابل مشاهده و Cache است؛ "GET /v2/products" فقط الگوی تازهٔ ServeMux است. نسخه در Header (Header versioning) با درخواست انتخاب میشود. Stripe نسخه را با تاریخ و Codename نامگذاری میکند؛ نسخهٔ جاری ثبتشده 2026-11-18.endive است. از 2024-09-30.acacia نسخهٔ ماهانه بدون Breaking change و سالی دو Major release دارد؛ Stripe-Version در curl پیشفرض Account را Override میکند. GitHub از X-GitHub-Api-Version استفاده میکند و میگوید "Requests without the X-GitHub-Api-Version header will default to use the 2022-11-28 version". طبق AIP-185 نسخهٔ اصلی تازه نباید به نسخهٔ قبلی وابسته باشد، اما معمولاً Service layer مشترک است.
1 v1 live: GET /v1/products -> dto.ProductView{price_cents}
2 need: price as {"amount":"9.00","currency":"EUR"} breaking
3 add GET /v2/products -> dtov2.ProductView{price{...}} ; same service.List
4 v1 responses: Deprecation (RFC 9745) and Sunset (RFC 8594) headers, docs say "v1 ends 2027-06-30"
5 traffic on /v1 falls to 0 (metrics by r.Pattern) -> remove v1 routes and DTOsسناریوی واقعی: موبایلهای API عمومی دیر Update میشوند؛ کلاینتهای داخلی همزمان Deploy میشوند و شاید Versioning نخواهند؛ شریک به نسخهٔ تاریخدار Pin شده؛ v2 صفحهبندی شمارهای را به Cursor تبدیل میکند.
| راهبرد | مثال | Routing در Go | Cache | مصرفکننده |
|---|---|---|---|---|
| مسیر (Path) | /v1/products | یک Pattern برای هر نسخه | طبیعی | Google APIs و این فصل |
| Header تاریخدار | Stripe-Version: 2026-11-18.endive | انتخاب DTO در Middleware | نیازمند Vary | Stripe |
| Header نامدار | X-GitHub-Api-Version: 2022-11-28 | Middleware | نیازمند Vary | GitHub REST |
| Media type | Accept: application/vnd.acme.v2+json | Content negotiation | نیازمند Vary | بعضی Hypermedia APIها |
| بدون نسخه، فقط تغییر افزایشی | هیچ | طبیعی | API داخلی با Deploy همزمان |
راهحل / نحوهٔ استفاده: نسخه در لبه، یعنی Route و DTO، بماند؛ نه داخل Service. مقایسهٔ راهبردها در API Versioning است. TestMuxErrorsBecomeProblems نشان میدهد /v2/products ناشناخته یک Problem با 404 میگیرد.
قرارداد OpenAPI 3.1 و تستی که آن را درست نگه میدارد حیاتی
به زبان ساده: قرارداد (Contract) در openapi.json همهٔ عملیات را شرح میدهد: مسیر، پارامتر، Schema درخواست و پاسخ، Header و پاسخ خطا. ابزارها از آن مستندات، کلاینت و Validation ترافیک میسازند. تست سند را با مسیرهای واقعاً ثبتشده مقایسه میکند تا از اجرا فاصله نگیرد.
بدفهمی رایج: «OpenAPI فقط Documentation است.» قرارداد قابل خواندن برای ماشین است و مستندات یکی از خروجیهاست. تعریف خود Spec: "defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code". نسخههای 3.0 و 3.1 هم یکسان نیستند: 3.1، Schema Object را با JSON Schema 2020-12 همراستا و webhooks سطح بالا را اضافه کرد. در READMEِ oapi-codegen، type: [T, "null"] روش 3.1 برای Nullability است؛ 3.0 از nullable: true استفاده میکرد. ابزار صرفاً 3.0 ممکن است سند 3.1 را رد کند.
تعریف: سند openapi: "3.1.0"، info، servers، paths با کلید Method کوچک و components شامل schemas، parameters و responses دارد. اینجا یک پاسخ Problem برای همهٔ خطاها مشترک است؛ فیلد سرور readOnly و ProductWrite دارای additionalProperties: false است تا با DisallowUnknownFields بخواند. پاسخ Product یک Object مستقل است، نه allOf: [ProductWrite, ...]: شاخههای allOf طبق Spec "are validated independently" و محدودیت Write، id و version را رد میکرد. servers برابر / است تا Docs به Origin خودش درخواست بزند؛ If-Match، Idempotency-Key و Link هم مستندند. سند با //go:embed در Binary و در /openapi.json سرو میشود. TestContractMatchesRoutes همهٔ Paths را به "METHOD /path" تبدیل و با httpapi.Routes() مقایسه میکند؛ Syntax {id} میان Go 1.22 و OpenAPI مشترک است. تست TestResponsesMatchSchemas بدنهٔ واقعی محصول، فهرست و دو Problem را با Schemaها بررسی میکند؛ Checker چهلخطی آن type، enum، required، properties، additionalProperties، items، allOf و $ref را میفهمد و همان اشتباه allOf نسخهٔ اول را پیدا کرد.
1 developer adds {"GET /v1/products/{id}/history", handleHistory(...), true} to routes
2 go test ./httpapi
3 --- FAIL: TestContractMatchesRoutes
spec [DELETE /v1/products/{id} GET /v1/products ... ]
routed [DELETE /v1/products/{id} GET /v1/products GET /v1/products/{id}/history ...]
4 developer documents the operation in openapi.json -> test passes -> docs and clients see itسناریوی واقعی: تیم Frontend در هر Merge کلاینت TypeScript میسازد؛ Partner portal مرجع را نمایش میدهد؛ Gateway از Spec برای Routing و Validation استفاده میکند؛ CI با oasdiff یا ابزار مشابه تغییر ناسازگار را نسبت به Release قبلی میگیرد.
| نسخه | انتشار | گویش Schema | نکته |
|---|---|---|---|
| Swagger 2.0 | 2014-09-08 | زیرمجموعهٔ JSON Schema | خروجی swaggo/swag v1؛ definitions و basePath |
| OpenAPI 3.0.x | 3.0.0 در 2017-07-26 | زیرمجموعهٔ توسعهیافته، nullable | components، requestBody، servers |
| OpenAPI 3.1.0 | 2021-02-15 | ابرمجموعهٔ JSON Schema 2020-12 | webhooks، آرایهٔ type برای Nullability |
| OpenAPI 3.1.1 | انتشار اصلاحی | همان | روشنسازیها |
| OpenAPI 3.2.x | شاخهٔ تازه، 3.2.1 | همان | عملیات query و additionalOperations طبق READMEِ oapi-codegen |
راهحل / نحوهٔ استفاده: سند کنار کد باشد؛ Embed، Serve و با Routeها تست شود. اگر اجرای Runtime قرارداد را هم میخواهید، Request validation از سند با openapi3filter در kin-openapi اضافه کنید.
{
"openapi": "3.1.0",
"info": {
"title": "Products API",
"version": "1.0.0",
"description": "Chapter example: CRUD, merge-patch, ETag/If-Match, Idempotency-Key, keyset pagination, RFC 9457 errors."
},
"servers": [{ "url": "/", "description": "Same origin as this document; tools may override (for example https://api.example.test)" }],
"paths": {
"/v1/products": {
"get": {
"operationId": "listProducts",
"summary": "List products (filter, sort, cursor pagination)",
"parameters": [
{ "name": "limit", "in": "query", "schema": { "type": "integer", "minimum": 0, "maximum": 100, "default": 20 } },
{ "name": "cursor", "in": "query", "description": "Opaque token from next_cursor", "schema": { "type": "string" } },
{ "name": "status", "in": "query", "schema": { "$ref": "#/components/schemas/Status" } },
{ "name": "min_price", "in": "query", "schema": { "type": "integer", "minimum": 0 } },
{ "name": "max_price", "in": "query", "schema": { "type": "integer", "minimum": 0 } },
{ "name": "sort", "in": "query", "schema": { "type": "string", "enum": ["created_at", "-created_at", "price", "-price", "name", "-name"], "default": "-created_at" } }
],
"responses": {
"200": {
"description": "One page",
"headers": { "Link": { "description": "rel=\"next\" URL when has_more is true", "schema": { "type": "string" } } },
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductList" } } }
},
"400": { "$ref": "#/components/responses/Problem" }
}
},
"post": {
"operationId": "createProduct",
"summary": "Create a product",
"parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
"requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductWrite" } } } },
"responses": {
"201": {
"description": "Created",
"headers": { "Location": { "schema": { "type": "string" } }, "ETag": { "schema": { "type": "string" } } },
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } }
},
"400": { "$ref": "#/components/responses/Problem" },
"409": { "$ref": "#/components/responses/Problem" },
"422": { "$ref": "#/components/responses/Problem" }
}
}
},
"/v1/products/{id}": {
"parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
"get": {
"operationId": "getProduct",
"responses": {
"200": { "description": "The product", "headers": { "ETag": { "schema": { "type": "string" } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
"304": { "description": "Not modified (If-None-Match)" },
"404": { "$ref": "#/components/responses/Problem" }
}
},
"put": {
"operationId": "replaceProduct",
"parameters": [{ "$ref": "#/components/parameters/IfMatch" }],
"requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductWrite" } } } },
"responses": {
"200": { "description": "Replaced", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
"412": { "$ref": "#/components/responses/Problem" },
"422": { "$ref": "#/components/responses/Problem" },
"428": { "$ref": "#/components/responses/Problem" }
}
},
"patch": {
"operationId": "patchProduct",
"parameters": [{ "$ref": "#/components/parameters/IfMatch" }],
"requestBody": { "required": true, "content": { "application/merge-patch+json": { "schema": { "type": "object" } } } },
"responses": {
"200": { "description": "Patched", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
"412": { "$ref": "#/components/responses/Problem" },
"415": { "$ref": "#/components/responses/Problem" },
"422": { "$ref": "#/components/responses/Problem" },
"428": { "$ref": "#/components/responses/Problem" }
}
},
"delete": {
"operationId": "deleteProduct",
"parameters": [{ "$ref": "#/components/parameters/IfMatch" }],
"responses": {
"204": { "description": "Deleted" },
"404": { "$ref": "#/components/responses/Problem" },
"412": { "$ref": "#/components/responses/Problem" },
"428": { "$ref": "#/components/responses/Problem" }
}
}
}
},
"components": {
"parameters": {
"IfMatch": { "name": "If-Match", "in": "header", "required": true, "schema": { "type": "string" }, "example": "\"v3\"" },
"IdempotencyKey": { "name": "Idempotency-Key", "in": "header", "schema": { "type": "string", "maxLength": 255 } }
},
"responses": {
"Problem": { "description": "RFC 9457 problem", "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/Problem" } } } }
},
"schemas": {
"Status": { "type": "string", "enum": ["draft", "active", "archived"] },
"ProductWrite": {
"type": "object",
"additionalProperties": false,
"required": ["sku", "name", "price_cents", "currency", "status"],
"properties": {
"sku": { "type": "string", "minLength": 3, "maxLength": 32 },
"name": { "type": "string", "minLength": 1, "maxLength": 200 },
"price_cents": { "type": "integer", "minimum": 0, "maximum": 100000000 },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" },
"status": { "$ref": "#/components/schemas/Status" },
"tags": { "type": "array", "maxItems": 10, "items": { "type": "string", "minLength": 1, "maxLength": 30 } }
}
},
"Product": {
"description": "Response representation. Not an allOf over ProductWrite: allOf branches are validated independently, so ProductWrite's additionalProperties false would reject id and version.",
"type": "object",
"additionalProperties": false,
"required": ["id", "sku", "name", "price_cents", "currency", "status", "tags", "version", "created_at", "updated_at"],
"properties": {
"id": { "type": "string", "readOnly": true },
"sku": { "type": "string", "minLength": 3, "maxLength": 32 },
"name": { "type": "string", "minLength": 1, "maxLength": 200 },
"price_cents": { "type": "integer", "minimum": 0, "maximum": 100000000 },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" },
"status": { "$ref": "#/components/schemas/Status" },
"tags": { "type": "array", "items": { "type": "string" } },
"version": { "type": "integer", "readOnly": true },
"created_at": { "type": "string", "format": "date-time", "readOnly": true },
"updated_at": { "type": "string", "format": "date-time", "readOnly": true }
}
},
"ProductList": {
"type": "object",
"required": ["data", "has_more"],
"properties": {
"data": { "type": "array", "items": { "$ref": "#/components/schemas/Product" } },
"next_cursor": { "type": "string" },
"has_more": { "type": "boolean" }
}
},
"Problem": {
"type": "object",
"properties": {
"type": { "type": "string", "format": "uri-reference", "default": "about:blank" },
"title": { "type": "string" },
"status": { "type": "integer" },
"detail": { "type": "string" },
"instance": { "type": "string" },
"request_id": { "type": "string" },
"errors": {
"type": "array",
"items": { "type": "object", "properties": { "pointer": { "type": "string" }, "detail": { "type": "string" } } }
}
}
}
}
}
}// Package openapi embeds the hand-written OpenAPI 3.1 document and serves it
// together with an interactive reference page.
package openapi
import (
_ "embed"
"html/template"
"net/http"
)
//go:embed openapi.json
var spec []byte
// Spec returns the embedded document (for the contract test).
func Spec() []byte { return spec }
// SpecHandler serves GET /openapi.json.
func SpecHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "public, max-age=300")
_, _ = w.Write(spec)
})
}
// docsPage loads Scalar's API reference from its CDN, as in Scalar's README.
// Pin the package version in production; Swagger UI (swagger-ui-dist) can be
// served the same way.
var docsPage = template.Must(template.New("docs").Parse(`<!doctype html>
<html>
<head>
<title>Products API reference</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div id="app"></div>
<script type="module">
import { createApiReference } from 'https://cdn.jsdelivr.net/npm/@scalar/api-reference/esm.js'
createApiReference('#app', { url: {{.}} })
</script>
</body>
</html>
`))
// DocsHandler serves GET /docs pointing at specURL.
func DocsHandler(specURL string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = docsPage.Execute(w, specURL)
})
}مقایسهٔ swaggo/swag، oapi-codegen و ogen و کلاینتهای تولیدشده مهم
به زبان ساده: دو جهت داریم. کدمحور (Code-first): Go مینویسید و از Commentها Spec میسازید، مثل swaggo/swag؛ huma از Typeهای Go در Runtime سند میسازد. قراردادمحور (Spec-first): Spec مینویسید و oapi-codegen یا ogen رابط سرور، Model و کلاینت Go میسازند. حاصل هر دو میتواند کلاینت تولیدشده (Generated client) با متد تایپدار باشد، بهجای HTTP دستی.
بدفهمی رایج: «swag خروجی OpenAPI 3 دارد.» خط پایدار نه: "Swag converts Go annotations to Swagger Documentation 2.0". خروجی 3.1 فقط با Flagِ --v3.1 در شاخهٔ v2 است؛ آخرین Tag ثبتشده در Module proxy، v2.0.0-rc6 در سپتامبر ۲۰۲۶ است. Spec-first هم الزاماً کندتر نیست: Strict server در oapi-codegen برای هر عملیات یک متد تایپدار میخواهد و JSON و Header را خودش مدیریت میکند.
تعریف: swag init Commentهایی مثل // @Summary، // @Param id path int true "Account ID"، // @Success و // @Router را میخواند و پوشهٔ docs با docs/docs.go میسازد که main Import میکند. http-swagger برای net/http، gorilla/mux و chi و Pluginهای gin، echo و fiber رابط Swagger UI را برای doc.json سرو میکنند. oapi-codegen در نسخهٔ ثبتشدهٔ v2.9.0 و مسیر ماژول github.com/oapi-codegen/oapi-codegen/v2 از v2.3.0، ورودی OpenAPI 3.0 و 3.1 میگیرد و std-http-server، chi-server، echo-server، gin-server، fiber-server، gorilla-server و iris-server، بهاضافهٔ strict-server و Client تولید میکند. README میگوید "requires Go 1.26+ to build and install. The generated code requires Go 1.26+ as well". ogen نسخهٔ v1.25.0 با go 1.26.0 در go.mod، یک "OpenAPI v3 Code Generator for Go" با "No reflection or interface{}" است: JSON تولیدشده با go-faster/jx، "Validation is code-generated according to spec"، Routerِ Static radix، Wrapperهای Optional[T]/Nullable[T]، OpenTelemetry و سرو Spec و Swagger UI با WithDocs.
spec-first (oapi-codegen, expected, not run: needs Go 1.26 for the generated code)
1 oapi-codegen.yaml package: api · generate: {std-http-server: true, strict-server: true, models: true, client: true}
2 go tool oapi-codegen -config oapi-codegen.yaml openapi.json > api/api.gen.go
3 type StrictServerInterface interface { ListProducts(ctx, ListProductsRequestObject) (ListProductsResponseObject, error); ... }
4 you write: type Server struct{ svc *service.Service } + one method per operation
5 mux := http.NewServeMux(); api.HandlerFromMux(api.NewStrictHandler(srv, nil), mux)
6 clients: api.NewClientWithResponses("https://api.example.test") -> typed ListProductsWithResponseسناریوی واقعی: Monolith مبتنی بر Gin با Annotation سریع مستند میشود؛ تیم Platform ابتدا فایل OpenAPI را Review و سپس سرور Go و کلاینت TypeScript میسازد؛ سرویس حساس به تأخیر ogen را برای JSON تولیدشده انتخاب میکند؛ تیم SDK از یک سند برای پنج زبان Client میسازد.
| swaggo/swag | oapi-codegen | ogen | Spec دستی + تست Drift، این فصل | |
|---|---|---|---|---|
| جهت | Code-first با Comment | Spec-first | Spec-first | Spec-first، کد دستی |
| نسخهٔ Spec | Swagger 2.0 در v1.16.6؛ 3.1 با --v3.1 در v2 RC | خواندن 3.0 و 3.1 و عملیات 3.2 | OpenAPI v3 | 3.1.0 |
| خروجی | Spec، docs.go | رابط سرور، Strict server، Model، Client | Server، Client، Validation، JSON codec، Router | هیچ |
| Router | gin، echo، fiber، net/http، chi، gorilla/mux و غیره؛ Pluginهای UI | net/http، Chi، Echo، Fiber، Gin، gorilla، Iris | Router خودش به شکل http.Handler | ServeMux شما |
| وابستگی Runtime | Handlerِ Swagger UI | github.com/oapi-codegen/runtime | ogen runtime، go-faster/jx | ندارد |
| حداقل Go | go 1.18 در ماژول | 1.26+ برای خروجی | go 1.26.0 در ماژول | انتخاب شما؛ اینجا 1.24 |
| خطر Drift | Comment در برابر کد | بخش تولیدشده ندارد | بخش تولیدشده ندارد | تست میگیرد |
| بهترین کاربرد | کد موجود، Docs سریع | قرارداد اول Review میشود، کلاینت زیاد | Performance و Type سختگیر | API کوچک، آموزش، بدون Generator |
راهحل / نحوهٔ استفاده: Generator را با Directiveِ tool در Go 1.24 ثابت کنید: go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@v2.9.0، سپس go tool oapi-codegen .... فایل تولیدشده را Version control کنید و CI با تغییر خروجی Regeneration شکست بخورد. کلاینت دستی زیر نمونهٔ چیزی است که Generator میسازد؛ متد All با Iterator از نوع Range-over-func در Go 1.23، next_cursor را دنبال میکند.
// Package client is a small typed client of the API: the kind of code an
// OpenAPI generator (oapi-codegen, ogen) writes for you from openapi.json.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"iter"
"net/http"
"net/url"
"academy/rest-api-project/dto"
"academy/rest-api-project/problem"
)
// Client talks to one base URL.
type Client struct {
BaseURL string
HTTP *http.Client
}
// Error is a non-2xx answer, decoded from application/problem+json.
type Error struct{ Problem problem.Problem }
func (e *Error) Error() string {
return fmt.Sprintf("%d %s: %s", e.Problem.Status, e.Problem.Title, e.Problem.Detail)
}
// Create posts a product with an Idempotency-Key so it is safe to retry.
func (c *Client) Create(ctx context.Context, key string, in dto.ProductWrite) (dto.ProductView, error) {
body, _ := json.Marshal(in)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/v1/products", bytes.NewReader(body))
if err != nil {
return dto.ProductView{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", `"`+key+`"`)
var out dto.ProductView
return out, c.do(req, http.StatusCreated, &out)
}
// All iterates every product matching query, following next_cursor page by
// page (range-over-func, Go 1.23). Stop early by breaking out of the loop.
func (c *Client) All(ctx context.Context, query url.Values) iter.Seq2[dto.ProductView, error] {
return func(yield func(dto.ProductView, error) bool) {
q := url.Values{}
for k, v := range query {
q[k] = v
}
for {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/v1/products?"+q.Encode(), nil)
if err != nil {
yield(dto.ProductView{}, err)
return
}
var page dto.ListView
if err := c.do(req, http.StatusOK, &page); err != nil {
yield(dto.ProductView{}, err)
return
}
for _, p := range page.Data {
if !yield(p, nil) {
return
}
}
if !page.HasMore {
return
}
q.Set("cursor", page.NextCursor)
}
}
}
func (c *Client) do(req *http.Request, want int, out any) error {
hc := c.HTTP
if hc == nil {
hc = http.DefaultClient
}
resp, err := hc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != want {
var e Error
_ = json.NewDecoder(resp.Body).Decode(&e.Problem)
e.Problem.Status = resp.StatusCode
return &e
}
return json.NewDecoder(resp.Body).Decode(out)
}سرو کردن مستندات API با Swagger UI / Scalar تکمیلی
به زبان ساده: سرویس قراردادش را در /openapi.json و صفحهٔ مرجع تعاملی را در /docs میدهد. مرورگر قرارداد را بار میکند؛ اینجا نمایشگر Scalar است، Swagger UI هم همین الگو را دارد.
بدفهمی رایج: «صفحهٔ مستندات (API documentation) به Deploy جدا نیاز دارد.» یک HTML ثابت که JavaScript bundle را بار کند و به /openapi.json اشاره کند کافی است. سرو Docs از خود API باعث میشود نسخهٔ در حال اجرا را توصیف کند. تصمیم اصلی امنیتی است: /docs عمومی باشد؟ بارگیری Script از CDN مجاز است؟
تعریف: READMEِ Scalar میگوید "All you need is a single HTML file": createApiReference را از https://cdn.jsdelivr.net/npm/@scalar/api-reference/esm.js Import و با URL سند فراخوانی میکنید. Swagger UI با بستهٔ swagger-ui-dist منتشر میشود: "a dependency-free module that includes everything you need to serve Swagger UI in a server-side project"؛ یا پوشهٔ /dist را روی سرور کپی میکنید. ogen میتواند سند و UI را در /docs/، /docs/openapi.json و /docs/openapi.yaml Embed کند؛ http-swagger در swag، UI را برای doc.json تولیدشده میدهد.
1 browser GET /docs -> HTML (html/template escapes the spec URL into the script)
2 script import from CDN -> createApiReference('#app', { url: "/openapi.json" })
3 browser GET /openapi.json -> embedded spec, Cache-Control: public, max-age=300
4 "Try it" uses servers[0].url = "/": real requests to the same origin (no CORS needed)سناریوی واقعی: همهٔ سرویسهای Platform داخلی /docs پشت SSO دارند؛ سایت Docs عمومی از همان سند در CI ساخته میشود؛ محیط بسته CDN را مسدود میکند و Bundle باید Vendor و با //go:embed داخل Binary قرار گیرد.
| انتخاب | میزبانی | نکته |
|---|---|---|
| Scalar با Script از CDN | یک HTML؛ این فصل | نسخهٔ Package را در Production ثابت کنید |
Swagger UI، swagger-ui-dist | کپی /dist و سرو با http.FileServerFS | گزینهٔ کلاسیک با کنسول "Try it out" |
ogen WithDocs | Handler تولیدشده | Spec و UI از بستهٔ تولیدشده |
swag + http-swagger | بستهٔ docs تولیدشده | سند Swagger 2.0 |
راهحل / نحوهٔ استفاده: openapi.go بالا را ببینید. Content-Security-Policy فقط CDN انتخابی را مجاز کند، یا Bundle را Embed کنید.
تست End-to-end با httptest و Repository حافظهای حیاتی
به زبان ساده: اغلب تستهای API باید درخواست واقعی HTTP را از زنجیرهٔ واقعی Handler، شامل Routing، Middleware، Decode، نگاشت خطا و Service، به Repository حافظهای بفرستند. httptest.NewServer در Process تست Listener واقعی میدهد؛ مخزن حافظهای (In-memory repository) برای هر تست Store تازه، سریع و مستقل میسازد.
بدفهمی رایج: «هر Handler را با Mock سرویس Unit-test کنیم.» این تستها پیادهسازی را تکرار میکنند و Method اشتباه Route، ترتیب غلط Middleware، نبودن Content-Type و Status متفاوت از Spec را نمیبینند. Ryer میگوید "I err on the side of end-to-end testing at this level, rather than unit testing all the pieces inside" و "If I diligently test every layer, I can end up saying the same things multiple times in slightly different ways." تست واحد برای منطق خالص مثل Merge patch، Cursor codec، Validation و قاعدهٔ Service همچنان ارزش دارد.
تعریف: سه سطح داریم: httptest.NewRecorder همراه handler.ServeHTTP برای جزء مستقل مثل problem و openapi؛ httptest.NewServer(httpapi.NewServer(deps)) با memrepo برای قرارداد HTTP؛ و app.Run در Goroutine برای کل برنامه. فایل httpapi_test.go چرخهٔ CRUD، هر کد خطا، دنبال کردن Link، 405 به شکل Problem، ساخت Idempotent، Rate limit hook و Drift قرارداد را میسنجد. app_test.go Config واقعی، Listener واقعی، انتظار Readiness، Typed client و Shutdown را پوشش میدهد. t.Context() از Go 1.24 درخواست را محدود و slog.DiscardHandler از همان نسخه Log را ساکت میکند. تست DB واقعیِ pgrepo میتواند Container PostgreSQL و همین آزمونها را پشت Build tag اضافه کند.
1 newAPI(t): svc := service.New(memrepo.New(), fakeClock, seqIDs)
2 srv := httptest.NewServer(httpapi.NewServer(Deps{...})) real TCP on 127.0.0.1
3 test: POST -> 201 · GET If-None-Match -> 304 · PATCH If-Match -> 200 v2
PATCH stale -> 412 · PUT no If-Match -> 428 · DELETE -> 204 · GET -> 404 problem
4 t.Cleanup(srv.Close); each test gets its own repository: no shared state, t.Parallel() safeسناریوی واقعی: تغییر ترتیب Middleware با تست 405 پیدا میشود؛ Endpoint تازه تا مستندسازی Contract test را میشکند؛ تبدیل تصادفی Validation به 500 با جدول خطاها مشخص میشود؛ CI کل Suite را حدود یک ثانیه بدون Docker اجرا میکند.
| سطح | ابزار | چه میگیرد | سرعت |
|---|---|---|---|
| منطق خالص | Table test | Merge patch، Cursor، Validation و قاعده | میکروثانیه |
| جزء (Component) | httptest.NewRecorder | خروجی یک Handler | میکروثانیه |
| قرارداد HTTP | httptest.NewServer + memrepo | Routing، Middleware، کد، Header و Spec drift | میلیثانیه |
| برنامه | app.Run + انتظار Readiness | Wiring، Config و Shutdown | دهها ms |
| ذخیرهسازی | PostgreSQL واقعی در Container | SQL، Index و Constraint | ثانیه |
راهحل / نحوهٔ استفاده: Suite زیر مشخصات اجرایی API است. جزئیات httptest، Table test و Coverage در Testing & Benchmarking است.
package httpapi_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"academy/rest-api-project/dto"
"academy/rest-api-project/httpapi"
"academy/rest-api-project/idempotency"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/openapi"
"academy/rest-api-project/pagination"
"academy/rest-api-project/problem"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
// newAPI starts the real handler stack over the in-memory repository: an
// end-to-end test of routing, middleware, decoding, service and storage.
func newAPI(t *testing.T, limiter httpapi.Limiter) *httptest.Server {
t.Helper()
at := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
n := 0
svc := service.New(memrepo.New(),
func() time.Time { at = at.Add(time.Second); return at },
func() string { n++; return fmt.Sprintf("prd_%03d", n) })
srv := httptest.NewServer(httpapi.NewServer(httpapi.Deps{
Logger: slog.New(slog.DiscardHandler),
Products: svc,
Cursors: pagination.Codec{Key: []byte("0123456789abcdef")},
Idempotency: idempotency.NewStore(24*time.Hour, time.Now),
Limiter: limiter,
MaxBodyBytes: 4 << 10,
}))
t.Cleanup(srv.Close)
return srv
}
func do(t *testing.T, method, url, ctype, body string, hdr ...string) *http.Response {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), method, url, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
if ctype != "" {
req.Header.Set("Content-Type", ctype)
}
for i := 0; i+1 < len(hdr); i += 2 {
req.Header.Set(hdr[i], hdr[i+1])
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { resp.Body.Close() })
return resp
}
func decodeAs[T any](t *testing.T, r *http.Response) T {
t.Helper()
var v T
if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
t.Fatal(err)
}
return v
}
const mug = `{"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"draft","tags":["kitchen"]}`
func TestCRUDLifecycle(t *testing.T) {
api := newAPI(t, nil)
created := do(t, "POST", api.URL+"/v1/products", "application/json", mug)
if created.StatusCode != 201 || created.Header.Get("ETag") != `"v1"` {
t.Fatalf("create: %d etag %q", created.StatusCode, created.Header.Get("ETag"))
}
loc := api.URL + created.Header.Get("Location")
if r := do(t, "GET", loc, "", "", "If-None-Match", `"v1"`); r.StatusCode != 304 {
t.Fatalf("conditional GET: %d", r.StatusCode)
}
// Merge patch: change the price, activate, delete the tags member.
patched := do(t, "PATCH", loc, "application/merge-patch+json",
`{"price_cents":1200,"status":"active","tags":null}`, "If-Match", `"v1"`)
view := decodeAs[dto.ProductView](t, patched)
if patched.StatusCode != 200 || view.PriceCents != 1200 || view.Version != 2 || len(view.Tags) != 0 {
t.Fatalf("patch: %d %+v", patched.StatusCode, view)
}
if r := do(t, "PATCH", loc, "application/merge-patch+json", `{"name":"Cup"}`, "If-Match", `"v1"`); r.StatusCode != 412 {
t.Fatalf("stale If-Match: %d, want 412", r.StatusCode)
}
if r := do(t, "PUT", loc, "application/json", mug); r.StatusCode != 428 {
t.Fatalf("PUT without If-Match: %d, want 428", r.StatusCode)
}
if r := do(t, "PATCH", loc, "application/merge-patch+json", `{"id":"prd_999"}`, "If-Match", `"v2"`); r.StatusCode != 400 {
t.Fatalf("patching a read-only member: %d, want 400", r.StatusCode)
}
if r := do(t, "DELETE", loc, "", "", "If-Match", `"v2"`); r.StatusCode != 204 {
t.Fatalf("delete: %d", r.StatusCode)
}
gone := do(t, "GET", loc, "", "")
p := decodeAs[problem.Problem](t, gone)
if gone.StatusCode != 404 || p.Type != "about:blank" || p.Title != "Not Found" || p.RequestID == "" {
t.Fatalf("after delete: %d %+v", gone.StatusCode, p)
}
}
func TestRequestErrorsAreProblems(t *testing.T) {
api := newAPI(t, nil)
url := api.URL + "/v1/products"
cases := []struct {
name, ctype, body string
status int
}{
{"validation", "application/json", `{"sku":"AB","name":"","price_cents":-1,"currency":"eur","status":"sold"}`, 422},
{"unknown field", "application/json", `{"sku":"MUG-2","colour":"red"}`, 400},
{"wrong type", "application/json", `{"sku":"MUG-2","price_cents":"9"}`, 400},
{"two objects", "application/json", mug + mug, 400},
{"media type", "text/plain", mug, 415},
{"too large", "application/json", `{"name":"` + strings.Repeat("x", 5000) + `"}`, 413},
}
// The same oversized body with an Idempotency-Key is cut by the idempotency
// middleware, which reads the body first.
if r := do(t, "POST", url, "application/json", `{"name":"`+strings.Repeat("x", 5000)+`"}`, "Idempotency-Key", `"big"`); r.StatusCode != 413 {
t.Fatalf("oversized body with a key: %d, want 413", r.StatusCode)
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := do(t, "POST", url, c.ctype, c.body)
if r.StatusCode != c.status || r.Header.Get("Content-Type") != problem.MediaType {
t.Fatalf("status %d (%s), want %d", r.StatusCode, r.Header.Get("Content-Type"), c.status)
}
p := decodeAs[problem.Problem](t, r)
if p.Status != c.status {
t.Fatalf("body status %d", p.Status)
}
if c.status == 422 {
var ptrs []string
for _, e := range p.Errors {
ptrs = append(ptrs, e.Pointer)
}
if !slices.Equal(ptrs, []string{"/sku", "/name", "/price_cents", "/currency", "/status"}) {
t.Fatalf("pointers %v", ptrs)
}
}
})
}
}
func TestPaginationFollowsLinkHeader(t *testing.T) {
api := newAPI(t, nil)
for i := range 7 {
body := fmt.Sprintf(`{"sku":"SKU-%d","name":"P%d","price_cents":%d,"currency":"EUR","status":"active"}`, i, i, 100*(i%3))
if r := do(t, "POST", api.URL+"/v1/products", "application/json", body); r.StatusCode != 201 {
t.Fatalf("seed %d: %d", i, r.StatusCode)
}
}
next := "/v1/products?sort=price&limit=3"
var ids []string
var firstCursor string
for next != "" {
r := do(t, "GET", api.URL+next, "", "")
page := decodeAs[dto.ListView](t, r)
for _, p := range page.Data {
ids = append(ids, p.ID)
}
if firstCursor == "" {
firstCursor = page.NextCursor
}
next = ""
if link := r.Header.Get("Link"); link != "" {
next = strings.TrimPrefix(strings.SplitN(link, ">", 2)[0], "<")
}
}
sorted := slices.Clone(ids)
slices.Sort(sorted)
if len(ids) != 7 || len(slices.Compact(sorted)) != 7 {
t.Fatalf("walked %v", ids)
}
// A cursor minted for sort=price is rejected for sort=name.
if r := do(t, "GET", api.URL+"/v1/products?sort=name&cursor="+firstCursor, "", ""); r.StatusCode != 400 {
t.Fatalf("cursor reuse with another sort: %d", r.StatusCode)
}
}
func TestMuxErrorsBecomeProblems(t *testing.T) {
api := newAPI(t, nil)
r := do(t, "DELETE", api.URL+"/v1/products", "", "")
if r.StatusCode != 405 || !strings.Contains(r.Header.Get("Allow"), "POST") || r.Header.Get("Content-Type") != problem.MediaType {
t.Fatalf("405: %d allow=%q ct=%q", r.StatusCode, r.Header.Get("Allow"), r.Header.Get("Content-Type"))
}
if r := do(t, "GET", api.URL+"/v2/products", "", ""); r.StatusCode != 404 || r.Header.Get("Content-Type") != problem.MediaType {
t.Fatalf("unknown version: %d", r.StatusCode)
}
}
func TestIdempotentCreate(t *testing.T) {
api := newAPI(t, nil)
key := "Idempotency-Key"
a := decodeAs[dto.ProductView](t, do(t, "POST", api.URL+"/v1/products", "application/json", mug, key, `"k-1"`))
retry := do(t, "POST", api.URL+"/v1/products", "application/json", mug, key, `"k-1"`)
b := decodeAs[dto.ProductView](t, retry)
if a.ID != b.ID || retry.StatusCode != 201 || retry.Header.Get(idempotency.ReplayedHeader) != "true" {
t.Fatalf("retry created a second product or was not replayed: %s vs %s", a.ID, b.ID)
}
// Without the key the same body hits the unique SKU: 409.
if r := do(t, "POST", api.URL+"/v1/products", "application/json", mug); r.StatusCode != 409 {
t.Fatalf("duplicate without key: %d", r.StatusCode)
}
}
type denyAll struct{}
func (denyAll) Allow(*http.Request) (bool, time.Duration) { return false, 1500 * time.Millisecond }
func TestRateLimitHook(t *testing.T) {
api := newAPI(t, denyAll{})
r := do(t, "GET", api.URL+"/v1/products", "", "", "X-Request-ID", "gw-123")
p := decodeAs[problem.Problem](t, r)
if r.StatusCode != 429 || r.Header.Get("Retry-After") != "2" || p.RequestID != "gw-123" {
t.Fatalf("429: %d retry-after %q %+v", r.StatusCode, r.Header.Get("Retry-After"), p)
}
}
// TestContractMatchesRoutes fails when a route is added without being
// documented, or documented without being routed.
func TestContractMatchesRoutes(t *testing.T) {
var doc struct {
Paths map[string]map[string]json.RawMessage `json:"paths"`
}
if err := json.Unmarshal(openapi.Spec(), &doc); err != nil {
t.Fatal(err)
}
var inSpec []string
for path, item := range doc.Paths {
for method := range item {
if method != "parameters" {
inSpec = append(inSpec, strings.ToUpper(method)+" "+path)
}
}
}
routed := httpapi.Routes()
slices.Sort(inSpec)
slices.Sort(routed)
if !slices.Equal(inSpec, routed) {
t.Fatalf("spec and routes differ:\nspec %v\nrouted %v", inSpec, routed)
}
}
func TestDocsAndSpecAreServed(t *testing.T) {
api := newAPI(t, nil)
if r := do(t, "GET", api.URL+"/openapi.json", "", ""); r.StatusCode != 200 {
t.Fatalf("spec: %d", r.StatusCode)
}
r := do(t, "GET", api.URL+"/docs", "", "")
b, _ := io.ReadAll(r.Body)
if r.StatusCode != 200 || !strings.Contains(string(b), "createApiReference") {
t.Fatalf("docs: %d", r.StatusCode)
}
}
// failingRepo makes every write fail with an internal error.
type failingRepo struct{ service.Repository }
func (failingRepo) Insert(context.Context, product.Product) error { return errors.New("disk on fire") }
// TestServerErrorCauseIsLoggedNotSent: the client gets a bare 500 problem,
// the access log gets the cause, also behind the idempotency middleware.
func TestServerErrorCauseIsLoggedNotSent(t *testing.T) {
var logs bytes.Buffer
svc := service.New(failingRepo{}, time.Now, func() string { return "prd_x" })
srv := httptest.NewServer(httpapi.NewServer(httpapi.Deps{
Logger: slog.New(slog.NewJSONHandler(&logs, nil)),
Products: svc,
Cursors: pagination.Codec{Key: []byte("0123456789abcdef")},
Idempotency: idempotency.NewStore(time.Hour, time.Now),
MaxBodyBytes: 4 << 10,
}))
defer srv.Close()
r := do(t, "POST", srv.URL+"/v1/products", "application/json", mug, "Idempotency-Key", `"k-500"`)
body, _ := io.ReadAll(r.Body)
if r.StatusCode != 500 || strings.Contains(string(body), "disk on fire") {
t.Fatalf("status %d, body leaks the cause: %s", r.StatusCode, body)
}
srv.Close() // flush: the access log line is written after the handler returns
if !strings.Contains(logs.String(), `"err":"create MUG-1: disk on fire"`) {
t.Fatalf("cause not logged:\n%s", logs.String())
}
}package memrepo_test
import (
"fmt"
"testing"
"time"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
// The in-memory repository must satisfy the same port as the SQL one.
var _ service.Repository = (*memrepo.Repo)(nil)
func TestKeysetWalkVisitsEveryRowOnce(t *testing.T) {
r := memrepo.New()
at := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
for i := range 25 {
// Five products share each price, so ties must be broken by id.
p := product.Product{ID: fmt.Sprintf("prd_%02d", i), SKU: fmt.Sprintf("SKU-%02d", i), PriceCents: int64(100 * (i % 5)), Status: product.StatusActive, CreatedAt: at}
if err := r.Insert(t.Context(), p); err != nil {
t.Fatal(err)
}
}
seen := map[string]bool{}
q := product.ListQuery{Sort: product.SortPrice, Desc: true, Limit: 7}
for pages := 0; ; pages++ {
rows, err := r.List(t.Context(), q)
if err != nil {
t.Fatal(err)
}
more := len(rows) > q.Limit
if more {
rows = rows[:q.Limit]
}
for _, p := range rows {
if seen[p.ID] {
t.Fatalf("row %s returned twice", p.ID)
}
seen[p.ID] = true
}
if !more {
break
}
c := product.CursorAfter(rows[len(rows)-1])
q.After = &c
}
if len(seen) != 25 {
t.Fatalf("visited %d rows, want 25", len(seen))
}
}
func TestUpdateChecksVersion(t *testing.T) {
r := memrepo.New()
p := product.Product{ID: "prd_1", SKU: "A", Version: 1}
_ = r.Insert(t.Context(), p)
p.Version = 2
if err := r.Update(t.Context(), p, 1); err != nil {
t.Fatal(err)
}
if err := r.Update(t.Context(), p, 1); err != product.ErrVersionMismatch {
t.Fatalf("stale write: got %v", err)
}
}خاموشی مرتب و Endpointهای سلامت حیاتی
به زبان ساده: خاموشی مرتب (Graceful shutdown) با SIGTERM ابتدا سرویس را «ناآماده» میکند تا Load balancer درخواست تازه نفرستد. کمی فرصت انتشار این وضعیت میدهد، سپس اتصال تازه را متوقف میکند و با مهلت محدود منتظر کارهای جاری میماند. /healthz میگوید Process زنده است؛ /readyz میگوید ترافیک بفرست.
بدفهمی رایج: «srv.Shutdown کافی است.» طبق مستند، "works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle". بدون Deadline تا ابد منتظر میماند. بستن فوری Listener هم با Load balancerی که هنوز از خروج Instance خبر ندارد Race میسازد؛ پس Readiness و تأخیر تخلیه (Drain delay) اول میآیند. Serve هم فوراً ErrServerClosed میدهد: "Make sure the program doesn't exit and waits instead for Shutdown to return".
تعریف: زنده بودن (Liveness) در /healthz نباید به پاییندست وابسته باشد؛ وگرنه قطعی DB همهٔ Podها را Restart میکند. آمادگی (Readiness) در /readyz نیازهای همین Instance مثل Ping مخزن را میسنجد و هنگام Draining شکست میخورد. Kubernetes میگوید "Readiness probes run on the container during its whole lifecycle" و Pod ناآماده "does not receive traffic through Kubernetes" Services. API server خود Kubernetes مسیرهای livez و readyz دارد و میگوید "The healthz endpoint is deprecated (since Kubernetes v1.16)". ترتیب Run: لغو Context با signal.NotifyContext، سپس draining = true و readyz برابر 503، انتظار API_DRAIN_DELAY، فراخوانی srv.Shutdown با API_SHUTDOWN_TIMEOUT، انتظار برگشت ErrServerClosed از Serve و در پایان nil.
t=0.000 SIGTERM ctx canceled · log "shutting down" drain_delay=1s timeout=10s
t=0.000 draining=true GET /readyz -> 503 {"detail":"shutting down"} (real run, see Lab)
t=0-1s load balancer marks the instance unready, stops new traffic
t=1.000 srv.Shutdown(ctx) listener closed, idle conns closed, waits for active requests
t=1.001 Serve returns ErrServerClosed -> Run returns nil -> exit 0 · log "stopped"
if requests still run at t=11s: Shutdown returns context deadline exceeded -> exit 1سناریوی واقعی: Rolling deploy قبلاً موج 502 میداد؛ Export طولانی هنگام پایان Pod قطع میشد؛ Liveness وابسته به DB در Failover طوفان Restart ایجاد میکرد؛ تست بهجای Sleep منتظر /readyz میماند.
| Endpoint / تنظیم | پاسخ | بررسی | فیلد Kubernetes |
|---|---|---|---|
/healthz، Liveness | 200 تا وقتی Process HTTP سرو میکند | هیچ وابستگی بیرونی | livenessProbe |
/readyz، Readiness | 200 یا Problem با 503 | Ping مخزن و Draining flag | readinessProbe |
| Startup | اختیاری | Migration تمام، Cache گرم | startupProbe |
API_DRAIN_DELAY | فرصت Update شدن Endpointها | کمتر از terminationGracePeriodSeconds | |
API_SHUTDOWN_TIMEOUT | سقف زمان درخواست جاری | همان بودجه |
راهحل / نحوهٔ استفاده: Run در بعد این ترتیب را اجرا میکند. Signal، NotifyContext و Lifecycle در OS Processes, Signals & Graceful Shutdown است.
Log ساختیافته، شناسهٔ درخواست و نقطهٔ اتصال Rate limiting مهم
به زبان ساده: هر درخواست شناسه (Request ID) دارد؛ از X-Request-ID قابل اعتماد گرفته یا ساخته میشود. در Header پاسخ، هر Problem و یک خط JSON log میآید. نقطهٔ اتصال محدودسازی نرخ (Rate limiting hook) در Middleware پیشفرض کاری نمیکند؛ اگر Limiter بدهید 429 با Retry-After میدهد.
بدفهمی رایج: «متن خطا را در پاسخ بگذار تا مشتری گزارش کند.» Request ID را بدهید؛ علت در Log است. سیاست Rate limiting مثل Per-key، Per-IP، Global، Token bucket یا Sliding window هم معمولاً مستقل از Endpoint تغییر میکند و گاه در Gateway است؛ API فقط Hook و 429 یکدست میخواهد.
تعریف: Middlewareِ requestID شناسهٔ ورودی را با ^[A-Za-z0-9._-]{1,64}$ بررسی میکند تا Log injection ممکن نباشد، آن را زیر کلید غیر Exportشدهٔ Context میگذارد و Header را تنظیم میکند؛ problem.Write آن را به request_id میبرد. ثبت ساختیافته (Structured logging) در logRequests با Writer wrapper وضعیت را میگیرد و r.Pattern از Go 1.23 را Label کمتنوع مسیر میکند: "the ServeMux pattern (if any) that matched the request". اگر writeError از طریق SetError رکوردر علت داخلی را ثبت کرده باشد، سطح ERROR و علت در Log میآیند. recoverPanics، Panic را به Problem با 500 تبدیل میکند، ولی http.ErrAbortHandler را دوباره Panic میکند. رابط Limiter یک متد Allow(r) (ok bool, retryAfter time.Duration) دارد. RFC 6585 دربارهٔ 429 میگوید "indicates that the user has sent too many requests in a given amount of time". پیشنویس RateLimit نیز "defines the RateLimit-Policy and RateLimit HTTP header fields" تا سهمیه اعلام شود.
1 in X-Request-ID: gw-123 (valid) -> ctx + response header
2 out 429 Retry-After: 2 {"type":".../rate-limited","status":429,"request_id":"gw-123"}
3 log {"level":"INFO","msg":"request","method":"GET","path":"/v1/products",
"pattern":"GET /v1/products","status":200,"duration":41625,"request_id":"e924..."}
4 500 {"level":"ERROR",...,"err":"<internal cause>"} client sees only about:blank 500 + request_idسناریوی واقعی: پشتیبانی از Request ID تیکت فوراً Log را پیدا میکند؛ داشبورد p99 برحسب Pattern بهجای Path خام از انفجار Cardinality شناسهها در امان است؛ شریک پرترافیک 429 با زمان روشن Retry میگیرد؛ شناسهٔ ازپیشساختهٔ Gateway حفظ میشود.
| دغدغه | این فصل | محل آموزش |
|---|---|---|
| ترتیب Middleware | requestID → recover → log → rateLimit → mux | Middlewares |
| Token bucket / Sliding window | فقط رابط Limiter | Rate Limiting in Go |
Handler و Level در slog | JSON handler از Run | CLI Flags, Env & Logging |
| Request ID در ctx | کلید غیر Exportشده و Accessor | context |
| ردگیری (Traces) | اینجا نیست | Instrumentation از OpenTelemetry دور Handler |
راهحل / نحوهٔ استفاده:
package httpapi
import (
"context"
"crypto/rand"
"encoding/hex"
"log/slog"
"math"
"net/http"
"regexp"
"strconv"
"time"
"academy/rest-api-project/problem"
)
type requestIDKey struct{}
// RequestID returns the id the requestID middleware put in ctx.
func RequestID(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey{}).(string)
return id
}
var validRequestID = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
// requestID accepts a sane X-Request-ID from the caller (a gateway) or makes
// one, stores it in ctx and echoes it; problem.Write copies it into bodies.
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if !validRequestID.MatchString(id) {
b := make([]byte, 8)
_, _ = rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey{}, id)))
})
}
// statusRecorder remembers what the handler did, for the access log.
type statusRecorder struct {
http.ResponseWriter
status int
err error
}
func (s *statusRecorder) WriteHeader(code int) {
if s.status == 0 {
s.status = code
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Write(b []byte) (int, error) {
if s.status == 0 {
s.status = http.StatusOK
}
return s.ResponseWriter.Write(b)
}
// SetError lets writeError attach the internal cause of a 5xx.
func (s *statusRecorder) SetError(err error) { s.err = err }
// Unwrap keeps http.ResponseController working through the wrapper.
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
// logRequests writes one structured line per request.
func logRequests(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
level := slog.LevelInfo
attrs := []slog.Attr{
slog.String("method", r.Method), slog.String("path", r.URL.Path),
slog.String("pattern", r.Pattern), slog.Int("status", rec.status),
slog.Duration("duration", time.Since(start)), slog.String("request_id", RequestID(r.Context())),
}
if rec.err != nil {
level = slog.LevelError
attrs = append(attrs, slog.String("err", rec.err.Error()))
}
log.LogAttrs(r.Context(), level, "request", attrs...)
})
}
// recoverPanics turns a panic into a 500 problem instead of a dropped
// connection, and logs it with the request id.
func recoverPanics(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
if v == http.ErrAbortHandler {
panic(v)
}
log.ErrorContext(r.Context(), "panic", "value", v, "request_id", RequestID(r.Context()))
problem.Write(w, r, problem.New(http.StatusInternalServerError, "", "", ""))
}
}()
next.ServeHTTP(w, r)
})
}
// rateLimit is the hook: the policy lives behind Limiter.
func rateLimit(l Limiter, next http.Handler) http.Handler {
if l == nil {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ok, after := l.Allow(r); !ok {
w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(after.Seconds()))))
problem.Write(w, r, problem.New(http.StatusTooManyRequests, "rate-limited", "Too many requests", ""))
return
}
next.ServeHTTP(w, r)
})
}
// fallbackRecorder captures the mux's own 404/405 replies.
type fallbackRecorder struct {
header http.Header
status int
}
func (f *fallbackRecorder) Header() http.Header { return f.header }
func (f *fallbackRecorder) Write(b []byte) (int, error) { return len(b), nil }
func (f *fallbackRecorder) WriteHeader(code int) { f.status = code }
// problemFallback keeps ServeMux's routing (including 405 + Allow) but
// rewrites its plain-text 404 and 405 bodies as Problem Details.
func problemFallback(mux *http.ServeMux) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h, pattern := mux.Handler(r)
if pattern != "" {
mux.ServeHTTP(w, r)
return
}
rec := &fallbackRecorder{header: http.Header{}}
h.ServeHTTP(rec, r)
switch rec.status {
case http.StatusNotFound, http.StatusMethodNotAllowed:
if allow := rec.header.Get("Allow"); allow != "" {
w.Header().Set("Allow", allow)
}
problem.Write(w, r, problem.New(rec.status, "", "", ""))
default: // redirects (trailing slash, cleaned paths)
mux.ServeHTTP(w, r)
}
})
}سازوکار (Mechanics)
خواندن امن بدنهٔ درخواست حیاتی
تابع decode[T] در codec.go پنج بررسی را به این ترتیب انجام میدهد. هر شکست کد خودش را دارد:
| مرحله | کد | شکست | وضعیت |
|---|---|---|---|
| 1 | mime.ParseMediaType(r.Header.Get("Content-Type")) | Media type غایب یا متفاوت؛ پارامترهایی مثل charset مجازند | 415 |
| 2 | http.MaxBytesReader(w, r.Body, max) | عبور از سقف، *http.MaxBytesError میدهد؛ "prevents clients from accidentally or maliciously sending a large request" | 413 |
| 3 | dec.DisallowUnknownFields() سپس Decode(&v) | Syntax error، عضو ناشناخته ("object keys which do not match any non-ignored, exported fields") یا *json.UnmarshalTypeError | 400 |
| 4 | dec.Decode(&struct{}{}) باید io.EOF بدهد | مقدار JSON دوم برابر 400؛ عبور از سقف هنگام خواندن دادهٔ انتهایی با همان decodeProblem برابر 413 | 400 / 413 |
| 5 | v.Valid(ctx) | نقض قواعد (Violations) | 422 |
تصمیم برحسب نوع خطاست: errors.As برای *http.MaxBytesError و *json.UnmarshalTypeError. متن Decoder فقط در detail میرود، چون مبنای Go 1.27 دربارهٔ بازنویسی encoding/json روی encoding/json/v2 هشدار میدهد "the exact text of error messages may differ". استفادهٔ مستقیم از API نسخهٔ v2 نیز "rejects invalid UTF-8 in JSON strings and rejects duplicate names within a JSON object". این مهم است وقتی Proxy و سرویس دو عضو همنام مثل "price_cents" را متفاوت تفسیر کنند.
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strings"
"academy/rest-api-project/problem"
"academy/rest-api-project/validation"
)
// validator is what a request DTO implements to be checked after decoding.
type validator interface {
Valid(ctx context.Context) []validation.Violation
}
// decode reads exactly one JSON object of type T from a bounded body,
// rejects unknown fields, then validates it. Every failure is a ready-made
// Problem, so handlers stay linear.
func decode[T validator](w http.ResponseWriter, r *http.Request, maxBytes int64, mediaType string) (T, *problem.Problem) {
var v T
if p := requireMediaType(r, mediaType); p != nil {
return v, p
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBytes))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, decodeProblem(err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
if tooBig := new(http.MaxBytesError); errors.As(err, &tooBig) {
return v, decodeProblem(err) // the limit can trip while reading trailing data
}
return v, problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", "body must contain a single JSON object")
}
if errs := v.Valid(r.Context()); len(errs) > 0 {
return v, problem.Validation(errs)
}
return v, nil
}
func requireMediaType(r *http.Request, want string) *problem.Problem {
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mt != want {
return problem.New(http.StatusUnsupportedMediaType, "unsupported-media-type", "Unsupported media type",
fmt.Sprintf("Content-Type must be %s", want))
}
return nil
}
// decodeProblem maps decoder errors by type. Message texts of encoding/json
// are not a stable API (Go 1.27 says they may differ), so only the detail
// string carries them.
func decodeProblem(err error) *problem.Problem {
var tooBig *http.MaxBytesError
var typeErr *json.UnmarshalTypeError
switch {
case errors.As(err, &tooBig):
return problem.New(http.StatusRequestEntityTooLarge, "body-too-large", "Request body too large",
fmt.Sprintf("limit is %d bytes", tooBig.Limit))
case errors.As(err, &typeErr):
p := problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", "a field has the wrong JSON type")
p.Errors = []validation.Violation{{Pointer: "/" + strings.ReplaceAll(typeErr.Field, ".", "/"), Detail: "must be " + typeErr.Type.String()}}
return p
}
return problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", err.Error())
}
// encode writes v as JSON with status.
func encode[T any](w http.ResponseWriter, status int, v T) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}پاسخهای 404 و 405 به شکل Problem Details مهم
ServeMux برای مسیر ناموجود متن سادهٔ 404 و از Go 1.22 برای Method غلط روی مسیر موجود "a 405 Method Not Allowed error that lists the available methods in an Allow header" میدهد. ثبت مسیر فراگیر (Catch-all) با "/" برای سفارشی کردن پاسخ، 405 را هم میبلعد؛ چون با هر Method تطبیق دارد. problemFallback ابتدا Pattern را از mux.Handler(r) میپرسد. Pattern خالی یعنی Mux خودش پاسخ میدهد؛ پاسخ را در Recorder اجرا میکند، Status و Allow را نگه میدارد و بدنه را Problem Details میکند. درخواست Matchشده از mux.ServeHTTP میگذرد تا r.PathValue و r.Pattern تنظیم شوند؛ mux.Handler آنها را تنظیم نمیکند.
DELETE /v1/products (registered: GET, POST)
1 mux.Handler(r) -> (405 handler, pattern "")
2 recorder: status 405, Allow: GET, HEAD, POST
3 problem.Write 405 about:blank "Method Not Allowed" + Allow header (real output in the Lab)SQLِ Keyset و Indexهای لازم حیاتی
مقایسهٔ مقدار ردیف (Row-value comparison) در (price_cents, id) < ($3, $4) مطابق راهنمای PostgreSQL از چپ به راست است: "the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found". نتیجه همان ادامه پس از آخرین ردیف در ترتیب (price_cents, id) است. Index روی همین دو ستون اجازه میدهد PostgreSQL به موقعیت Seek و فقط LIMIT ردیف بخواند؛ در این مدل صفحهٔ 1,000 هزینهای مثل صفحهٔ 1 دارد. pgrepo.BuildList این SQL را تولید میکند و TestBuildListKeysetDesc آن را Assert میکند:
-- schema (pgrepo.Schema): one composite index per allowed sort
CREATE TABLE products (
id text PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price_cents bigint NOT NULL CHECK (price_cents >= 0),
currency char(3) NOT NULL,
status text NOT NULL,
tags jsonb NOT NULL DEFAULT '[]',
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX products_price_id ON products (price_cents, id);
-- page 2 of GET /v1/products?status=active&min_price=500&sort=-price&limit=20
SELECT id, sku, name, price_cents, currency, status, version, created_at, updated_at
FROM products
WHERE status = 'active' AND price_cents >= 500
AND (price_cents, id) < (1999, 'prd_42')
ORDER BY price_cents DESC, id DESC
LIMIT 21;
-- the offset version reads and discards 20,000 rows to return 20
SELECT * FROM products ORDER BY price_cents DESC, id DESC LIMIT 20 OFFSET 20000;
-- optimistic concurrency: a stale writer updates 0 rows
UPDATE products SET price_cents = 1200, version = 2, updated_at = now()
WHERE id = 'prd_42' AND version = 1;
-- idempotency keys shared by all instances
CREATE TABLE idempotency_keys (
scope text PRIMARY KEY, -- 'POST /v1/products <key>'
fingerprint text NOT NULL,
status int, -- NULL while in flight
response bytea,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO idempotency_keys (scope, fingerprint) VALUES ($1, $2) ON CONFLICT DO NOTHING;پاسخهای دقیق از اجرای واقعی مهم
| وضعیت | خط وضعیت | بدنهٔ خلاصهشده |
|---|---|---|
| ساخت | HTTP/1.1 201 Created، Etag: "v1"، Location: /v1/products/prd_fc89a65f13439790 | محصول با "version":1 |
| Retry با همان کلید | HTTP/1.1 201 Created، Idempotent-Replayed: true | بدنهٔ یکسان |
| اعتبارسنجی (Validation) | HTTP/1.1 422 Unprocessable Entity | "type":"https://api.example.test/problems/validation" و پنج errors |
GET شرطی، If-None-Match: W/"v1" | HTTP/1.1 304 Not Modified | ندارد |
If-Match: "v1", "v2" در برابر v2 | HTTP/1.1 200 OK، Etag: "v3" | محصول |
If-Match قدیمی | HTTP/1.1 412 Precondition Failed | "type":".../stale-version" |
بدون If-Match | HTTP/1.1 428 Precondition Required | "type":".../if-match-required" |
| Method غلط | HTTP/1.1 405 Method Not Allowed، Allow: GET, HEAD, POST | "type":"about:blank","title":"Method Not Allowed" |
| Cursor با Sort دیگر | 400 | "detail":"cursor: invalid or does not match the current filter and sort" |
limit=-1 | 400 | "detail":"limit: must not be negative" |
| Readiness هنگام Draining | 503 | "detail":"shutting down" |
خط وضعیت Go هنوز "Unprocessable Entity" از http.StatusText(422) میگوید، در حالی که نام RFC 9110، "Unprocessable Content" است؛ کلاینت باید عدد را مبنا بگیرد. Etag و X-Request-Id شکل Canonical حاصل textproto.CanonicalMIMEHeaderKey هستند؛ نام Header به بزرگی و کوچکی حرف حساس نیست.
حل مسئلههای کلاسیک (Solutions)
| مسئله | نشانه | راهحل | هزینه |
|---|---|---|---|
| خطا با 200 | کلاینت متن Parse میکند؛ Retry و Alert کورند | RFC 9457 و کد واقعی، یک writeError | یک بسته |
| انتساب انبوه (Mass assignment) | کلاینت version، id یا is_admin مینویسد | Write DTO و DisallowUnknownFields | کد Mapping |
| بدنهٔ نامحدود | جهش حافظه و Uploadِ Slow-loris | MaxBytesReader با 413 و Timeout سرور | یک Limit برای هر Route |
| گم شدن ویرایش (Lost update) | ویرایش بیصدا پاک میشود | ETag و If-Match با 412/428 و WHERE version = ? | کلاینت Header بفرستد |
| ساخت دوباره در Retry | دو سفارش یا دو برداشت | Idempotency-Key با Fingerprint و Replay | Store کلید |
| جابهجایی صفحه (Page drift) و کندی صفحهٔ عمیق | تکرار هنگام Scroll؛ صفحهٔ 10,000 کند | Keyset cursor، Index مرکب و Link | بدون دسترسی تصادفی به صفحه |
| تزریق Sort/Filter | SQL injection و Table scan | Allow-list به Column map و Filter تایپدار | یک Map |
| فاصلهٔ سند و اجرا (Spec drift) | Docs و Client غلط | Contract test یا Generation از Spec | یک تست |
| افشای جزئیات داخلی | Stack trace و SQL در خطا | 500 عمومی و Request ID؛ علت فقط در Log | ندارد |
| قطع درخواست در Deploy | موج 502 | readyz ناآماده، Drain delay، Shutdown با Timeout | چند ثانیه در Deploy |
main تستناپذیر | Wiring bug در Staging پیدا میشود | Run(ctx, args, getenv, stdout) و Constructor | ندارد |
گم شدن ویرایش: اصلاح در سه نقطه
تست TestLostUpdate در قبل نشان میدهد تغییر نام از کلاینت قدیمی، تغییر قیمت قبلی را پاک میکند. جلوگیری از Lost update سه جزء دارد: Handler، If-Match را اجباری میکند و بدون آن 428 میدهد؛ Service نسخه را سریع بررسی و 412 میدهد؛ Repository دوباره شرط را اتمیک در UPDATE ... WHERE version = $9 اعمال میکند، چون دو درخواست میتوانند همزمان از بررسی Service عبور کنند.
جابهجایی صفحهها (Page drift)
تستهای TestOffsetPagingRepeatsRows در Before و TestOffsetDriftVsKeyset در Pagination تکرار را بازسازی میکنند. TestKeysetWalkVisitsEveryRowOnce روی 25 ردیف با قیمتهای دارای تساوی پنجتایی و صفحههای 7تایی حرکت میکند و دقیقاً یکبار دیده شدن هر ردیف را Assert میکند؛ این فایدهٔ Tie-breaker با id است.
POST تکراری
TestRetryIsReplayed برای دو درخواست یکسان فقط یک بار Handler را اجرا میکند. TestStatusCodesFromTheDraft کدهای 400 برای کلید غایب، 409 برای Retry حین اجرا و 422 برای همان کلید با بدنهٔ متفاوت را پوشش میدهد. TestServerErrorsAreNotStored نشان میدهد 503 با همان کلید قابل Retry است. میان چند Instance، Map حافظهای را با جدول idempotency_keys بالا عوض کنید.
فاصلهٔ قرارداد و اجرا (Spec drift)
TestContractMatchesRoutes سند openapi.json را با httpapi.Routes() مقایسه میکند. این تست Schema را بررسی نمیکند؛ برای آن پاسخها را در تست با سند و openapi3filter از kin-openapi اعتبارسنجی کنید یا به کد تولیدشده بروید.
انتخاب (Choosing)
| وضعیت | انتخاب | تکنیک اضافه | دلیل |
|---|---|---|---|
| API داخلی کوچک، یک تیم | ServeMux و DTO دستی با این ساختار | Contract test در برابر Spec دستی | Generator برای نگهداری ندارید |
| API عمومی، زبانهای کلاینت زیاد | Spec-first با Strict server در oapi-codegen | Generated client و بررسی Breaking change در CI | سند خود محصول است |
| کد Gin/Echo موجود به Docs نیاز دارد | swaggo/swag | Annotation کنار Handler، Regeneration در CI | کمترین کار، خروجی Swagger 2.0 |
| مسیر پرترافیک و Type سختگیر | ogen | JSON و Validation تولیدشده | بدون Reflection |
| Code-first با OpenAPI 3.1 در Runtime | huma | Validation از نوعهای Go | Spec از Type، بدون Comment |
| قواعد Validation عمدتاً ساده | Valid(ctx) دستی | یک نوع Violation | بدون وابستگی، خطای روشن |
| فیلد و قاعدهٔ زیاد | go-playground/validator | RegisterTagNameFunc و پیام اختصاصی | کد کمتر |
| فهرست در حال رشد یا تغییر | Keyset cursor | Token مبهم رمزشده و Link | پایدار و سریع |
| جدول مدیریتی با شمارهٔ صفحه | Offset محدود | Total فقط اگر ارزان است | کاربر «صفحهٔ 3 از 9» میخواهد |
| Update با چند نویسنده | ETag و If-Match | نبود Header برابر 428 | بدون Lost update |
POST قابل Retry | Idempotency-Key | Store مشترک و Fingerprint | بدون تکرار |
| تغییر ناسازگار | Route و DTO نسخهٔ /v2 | Headerهای Deprecation، RFC 9745 و Sunset، RFC 8594 در v1 | کلاینت قدیمی کار میکند |
| قالب خطا | RFC 9457 | errors[] با JSON Pointer و request_id | استاندارد مشترک کلاینتها |
در معماری: از یک Process تا سیستم توزیعشده
مونولیت (Monolith): یک Process، یک Database
ساختار این صفحه برای برنامهٔ یکپارچه (Monolith) مناسب است: یک Binary، تابع Run بهعنوان Composition root، یک ServeMux و جدول همهٔ مسیرها، Service و Repository برای هر Aggregate و یک PostgreSQL. یکتایی با UNIQUE، Optimistic concurrency با ستون version، Idempotency key با جدول و Keyset با Index مرکب تأمین میشود. یک Transaction میتواند تغییر کسبوکار، پاسخ ذخیرهشده و ردیف Outbox را پوشش دهد. مثال: Backend فروشگاه با products، orders و customers که هرکدام service و Repository خودشان را در یک Process دارند. POST /v1/orders سفارش و پاسخ Idempotency-Key را در همان Transaction مینویسد؛ Crash بین آنها نباید سفارشی بسازد که Retry آن سفارش دوم بسازد.
مونولیت ماژولار و چند Database
در مونولیت ماژولار (Modular monolith)، بستهها به ماژولهای catalog، ordering و billing با API روشن تبدیل میشوند. هرکدام Service، رابط Repository و جدول یا Schema خود را دارد؛ هیچ ماژولی جدول دیگری را نمیخواند. لایهٔ HTTP یک NewServer میماند، ولی هر ماژول Routes table خودش را میدهد و OpenAPI از قطعههای ماژولها ساخته میشود. ordering برای قیمت، رابط Serviceِ catalog را صدا میزند، نه Repository آن را. اگر Billing به DB جدا برود، مرز Transaction هم جابهجا میشود: سفارش و فاکتور دیگر اتمیک نیستند؛ ordering رویداد Outbox مینویسد و billing آن را Idempotent مصرف میکند. Contract test همچنان یک Spec را با مسیرهای همهٔ ماژولها مقایسه میکند.
میکروسرویسها (Microservices)
هر میکروسرویس (Microservice) مالک API، Spec، DB و سیاست Versioning خودش است. الگوهای این صفحه در هر سرویس برقرارند و سه مورد قرارداد بین سرویسها میشوند. Problem Details قالب خطا را مشترک میکند تا Gateway یا BFF آن را عبور دهد یا تبدیل کند. Idempotency key هم عبور میکند: وقتی Checkout به Payments با Idempotency-Key: "order-1007-charge" درخواست میدهد، Retry پس از Timeout برداشت دوم نمیسازد، حتی اگر Checkout نتیجهٔ تلاش اول را نداند. Request ID یا traceparent استاندارد W3C نیز عبور میکند تا یک درخواست مشتری در پنج سرویس دنبال شود.
مثال جریان: موبایل → POST /v1/orders با کلید K → سرویس Orders اعتبارسنجی و ذخیرهٔ سفارش با K → فراخوانی POST /v1/payment-intents در Payments با کلید "order-ID-charge" → تماس Payments با شبکهٔ کارت → پاسخ 201 از Orders. Retry موبایل با K، همان 201 را میگیرد؛ Retry از Orders به Payments هم پاسخ ذخیرهشدهٔ Payments را میگیرد. Generated client از OpenAPI هر سرویس جای HTTP دستی را میگیرد و بررسی Breaking change در CI جلوی شکستن کلاینت تیم دیگر را میگیرد. Cursor و ETag در مرز سرویس مبهم میمانند؛ مصرفکننده نباید آنها را Parse کند. زنجیرهٔ همزمان Timeout و Budget لازم دارد؛ context و API Idempotency را ببینید.
دادهٔ توزیعشده: Replica، Cache، Shard و چند Region
نسخهٔ خواندنی (Read replica) تضمین خواندن نوشتهٔ خود (Read-your-writes) را میشکند: کلاینت PATCH میکند، فوراً GET از Replica میگیرد و نسخه و ETag قدیمی میبیند؛ Write بعدی 412 میگیرد. راهحل این است که Read بعد از Write برای چند ثانیه به Primary برود یا Write، Representation تازه را در پاسخ بدهد؛ این API روش دوم را دارد. Cache جلوی GET /v1/products/{id} میتواند از ETag و If-None-Match با 304 استفاده کند و هنگام Write باید Invalidate شود. Cache فهرست Cursorدار بهندرت ارزش دارد.
در طراحی چند Shard این فصل، Keyset روش صفحهبندی قابل استفاده است: هر Shard صفحهٔ بعد از Cursor را میدهد و مرحلهٔ Merge اولین N مورد را برمیدارد؛ OFFSET 10000 در مقابل یعنی خواندن 10,000 ردیف از هر Shard. Storeِ Idempotency باید در محدودهٔ کلید، مثلاً Tenant یا Region، سراسری باشد؛ وگرنه Retry در Region دیگر تکرار میسازد. در Active-active چند Region، بررسی version به نویسندهٔ واحد برای هر Resource در Home region یا Conflict resolution نیاز دارد؛ ETag جلوی پذیرش دو Write متعارض در دو Region مستقل را نمیگیرد.
مسیر مقیاسپذیری: 1×، 10×، 100×
| بار | چه عوض میشود | رویهٔ API |
|---|---|---|
| 1×، یک Instance | همهچیز در یک Process جا میشود | همین صفحه؛ Store حافظهای Idempotency فقط اینجا قابل قبول است |
| 10×، چند Instance پشت Load balancer | حالت مشترک باید از Process بیرون برود | کلیدها در PostgreSQL یا Redis؛ Readiness و Drain delay برای Rolling deploy؛ Rate limit هر کلید در Store مشترک یا Gateway؛ سقف limit برابر 100 |
| 100×، سرویس و فهرست سنگین و شریک زیاد | فهرست داغ، Retry و کلاینت زیاد | Keyset با Covering index؛ بدون Total؛ Generated client؛ CDN/ETag برای Read داغ؛ قرارداد نسخهدار با Deprecation header؛ حذف بار پیش از DB، Load Shedding |
آزمایشگاه (Lab)
1. اجرای تستها؛ نتیجهٔ واقعی
cd docs/snippets/go/rest-api-project/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok academy/rest-api-project/app 1.473s
# ok academy/rest-api-project/before 1.328s
# ok academy/rest-api-project/client 1.385s
# ? academy/rest-api-project/cmd/api [no test files]
# ok academy/rest-api-project/config 1.375s
# ok academy/rest-api-project/dto 1.385s
# ok academy/rest-api-project/httpapi 1.470s
# ok academy/rest-api-project/idempotency 1.361s
# ok academy/rest-api-project/memrepo 1.457s
# ok academy/rest-api-project/mergepatch 1.356s
# ok academy/rest-api-project/openapi 1.382s
# ok academy/rest-api-project/pagination 1.377s
# ok academy/rest-api-project/pgrepo 1.468s
# ok academy/rest-api-project/problem 1.492s
# ok academy/rest-api-project/product 1.483s
# ok academy/rest-api-project/service 1.481s
# ok academy/rest-api-project/validation 1.447s2. ساخت، Retry و Validation؛ نتیجهٔ واقعی
آزمایشهای 2 تا 5 یک نشست Shell هستند و همانطور که نوشته شده اجرا شدهاند؛ مرجع اجرا pipeline/sources/rest-api-project/lab-round1.sh.txt است. خروجی زیر متعلق به همان اجرای ثبتشده است و فقط Headerهای Date حذف شدهاند.
go build -o api ./cmd/api
API_CURSOR_KEY=0123456789abcdef API_ADDR=127.0.0.1:8088 API_DRAIN_DELAY=1s ./api > api.log 2>&1 &
PID=$!
B=http://127.0.0.1:8088
curl -si -X POST $B/v1/products -H 'Content-Type: application/json' \
-H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' -H 'X-Request-ID: lab-1' \
-d '{"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"draft","tags":["kitchen"]}' | tee create.txt
# HTTP/1.1 201 Created
# Content-Type: application/json
# Etag: "v1"
# Location: /v1/products/prd_fc89a65f13439790
# X-Request-Id: lab-1
# {"id":"prd_fc89a65f13439790","sku":"MUG-1","name":"Mug","price_cents":900,...,"tags":["kitchen"],"version":1,...}
LOC=$(grep -i '^Location:' create.txt | tr -d '\r' | cut -d' ' -f2) # /v1/products/prd_fc89a65f13439790
# the same POST again (a retry)
# HTTP/1.1 201 Created
# Etag: "v1"
# Idempotent-Replayed: true
# Location: /v1/products/prd_fc89a65f13439790 same product, nothing created
# X-Request-Id: 67fea3ffd3cdc8b3 the retry's own request id
curl -si -X POST $B/v1/products -H 'Content-Type: application/json' -H 'X-Request-ID: lab-2' \
-d '{"sku":"AB","name":"","currency":"eur","status":"sold"}'
# HTTP/1.1 422 Unprocessable Entity
# Content-Type: application/problem+json
# {"type":"https://api.example.test/problems/validation","title":"Request body failed validation",
# "status":422,"instance":"/v1/products","errors":[{"pointer":"/sku","detail":"must be at least 3"},
# {"pointer":"/name","detail":"is required"},{"pointer":"/price_cents","detail":"is required"},
# {"pointer":"/currency","detail":"must be upper case"},
# {"pointer":"/status","detail":"must be one of: draft active archived"}],"request_id":"lab-2"}3. درخواست شرطی و Merge patch؛ نتیجهٔ واقعی
curl -si $B$LOC -H 'If-None-Match: W/"v1"' # weak comparison
# HTTP/1.1 304 Not Modified
# Etag: "v1"
curl -si -X PATCH $B$LOC -H 'Content-Type: application/merge-patch+json' \
-H 'If-Match: "v1"' -d '{"price_cents":1200,"status":"active","tags":null}'
# HTTP/1.1 200 OK
# Etag: "v2"
# {...,"price_cents":1200,"currency":"EUR","status":"active","tags":[],"version":2,...}
curl -si -X PATCH $B$LOC -H 'Content-Type: application/merge-patch+json' -H 'If-Match: "v1"' -d '{"name":"Cup"}'
# HTTP/1.1 412 Precondition Failed
# {"type":"https://api.example.test/problems/stale-version","title":"Resource changed since you read it",
# "status":412,"detail":"GET it again and retry with the new ETag in If-Match",...}
curl -si -X PATCH $B$LOC -H 'Content-Type: application/merge-patch+json' -H 'If-Match: "v1", "v2"' -d '{"name":"Cup"}'
# HTTP/1.1 200 OK any listed tag may match
# Etag: "v3"
curl -si -X PUT $B$LOC -H 'Content-Type: application/json' \
-d '{"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"active"}'
# HTTP/1.1 428 Precondition Required
curl -si -X DELETE $B/v1/products
# HTTP/1.1 405 Method Not Allowed
# Allow: GET, HEAD, POST
# {"type":"about:blank","title":"Method Not Allowed","status":405,"instance":"/v1/products",...}4. دنبال کردن Cursor؛ نتیجهٔ واقعی
for i in 1 2 3 4; do
curl -s -o /dev/null -X POST $B/v1/products -H 'Content-Type: application/json' \
-d "{\"sku\":\"SKU-$i\",\"name\":\"Item $i\",\"price_cents\":${i}00,\"currency\":\"EUR\",\"status\":\"active\"}"
done # prices 100..400, plus MUG-1 at 1200
curl -si "$B/v1/products?sort=price&limit=2" > page1.txt
# HTTP/1.1 200 OK
# Link: </v1/products?cursor=KBODNt5ZckjAnijDw1_9e3s2yLMDLQPX37Ojh8Z0TaSJB58GbwO6lb1Zo3BxbdpQF5QqDTHDZluAkmB_EJqzwImqXQaAvbbij9Eq9f06UNoFXun5xA&limit=2&sort=price>; rel="next"
# page 1: SKU-1, SKU-2 has_more: true
NEXT=$(tail -1 page1.txt | python3 -c 'import sys,json;print(json.load(sys.stdin)["next_cursor"])')
curl -s "$B/v1/products?sort=price&limit=2&cursor=$NEXT"
# page 2: SKU-3, SKU-4 has_more: true (page 3 would hold MUG-1)
curl -s "$B/v1/products?sort=name&limit=2&cursor=$NEXT"
# {"type":".../invalid-query","status":400,"detail":"cursor: invalid or does not match the current filter and sort",...}Token نمایش base64url یک Nonce تصادفی و Ciphertext از AES-GCM است؛ Decode کردنش ID محصول، قیمت یا Query را آشکار نمیکند.
5. خاموشی مرتب؛ نتیجهٔ واقعی
kill -TERM $PID
sleep 0.3 # inside the 1 s drain delay
curl -s $B/readyz
# {"type":"about:blank","title":"Service Unavailable","status":503,"detail":"shutting down",...}
wait $PID; echo "exit=$?"
# exit=0
grep -E '"shutting down"|/readyz.*503|"stopped"' api.log
# {"level":"INFO","msg":"shutting down","drain_delay":"1s","timeout":"10s"}
# {"level":"INFO","msg":"request","path":"/readyz","pattern":"GET /readyz","status":503,...}
# {"level":"INFO","msg":"stopped"}6. تولید سرور با oapi-codegen؛ انتظار میرود، اجرا نشده
کد تولیدشده Go 1.26+ میخواهد، پس جزو ماژول snippet با go 1.24 نیست. در ماژولی جدا با go 1.26:
go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@v2.9.0
cat > oapi-codegen.yaml <<'YAML'
package: api
output: api/api.gen.go
generate:
std-http-server: true
strict-server: true
models: true
client: true
YAML
go tool oapi-codegen -config oapi-codegen.yaml openapi.json
# expected: api/api.gen.go with ServerInterface, StrictServerInterface, HandlerFromMux,
# ProductWrite/Product/Problem models and ClientWithResponses7. اجرای Repository با PostgreSQL؛ انتظار میرود، اجرا نشده
pgrepo.Schema را اعمال کنید. پس از Import کردن github.com/jackc/pgx/v5/stdlib، با Adapterِ database/sql در pgx و sql.Open("pgx", dsn) یک Pool باز کنید. در Run بهجای memrepo.New()، pgrepo.New(db) بدهید؛ نوع repo همان service.Repository بهاضافهٔ Ping است و این جایگزینی کامپایل میشود. روی Queryِ Keyset بخش سازوکار، EXPLAIN اجرا کنید. Plan مورد انتظار Index Scan Backward using products_price_id بدون Nodeِ Sort است و هزینهٔ صفحهٔ 1 و 1,000 یکسان انتظار میرود. Planِ Offset، OFFSET + LIMIT ردیف میخواند.
برای توسعهدهندگان PHP/Laravel
Laravel بسیاری از اجزای این فصل را با Convention میدهد. Route::apiResource('photos', PhotoController::class) پنج مسیر API را ثبت میکند و create و edit را کنار میگذارد. کلاس درخواست فرم (Form Request) که با php artisan make:request StorePostRequest ساخته میشود، rules() و authorize() دارد. Validation ناموفق برای درخواست منتظر JSON به 422 با {"message": ..., "errors": {...} } میرسد. API Resources به تعبیر مستند "a transformation layer that sits between your Eloquent models and the JSON responses" هستند: toArray برای تبدیل، whenLoaded برای پرهیز از N+1 و Resource بیرونی "wrapped in a data key". با JsonResource::withoutWrapping() این Wrapper خاموش میشود؛ مجموعهٔ صفحهبندیشده هم links و meta میگیرد. Laravel 13 منابع JSON:API هم دارد.
paginate، simplePaginate و cursorPaginate بهترتیب Offset با Total، Offset بدون Total و Keyset هستند؛ مستند میگوید "cursor pagination works by constructing "where" clauses that compare the values of the ordered columns contained in the query". مواردی که پیشفرض Laravel نیستند Problem Details، ETag/If-Match، Idempotency-Key و سند OpenAPI هستند؛ مثل Go، Package یا Middleware خودتان لازم دارند.
// routes/api.php: Route::apiResource('products', ProductController::class);
public function store(StoreProductRequest $request): JsonResponse // rules() run first: 422 on failure
{
$product = Product::create($request->validated()); // only validated fields: no mass assignment
return (new ProductResource($product))->response()->setStatusCode(201); // response() returns Illuminate\Http\JsonResponse
}
public function index(Request $request)
{
return ProductResource::collection(
Product::where('status', 'active')->orderBy('price_cents')->orderBy('id')->cursorPaginate(20)
); // {"data":[...],"links":{...},"meta":{...}}
}| Laravel | Go در این فصل |
|---|---|
Route::apiResource('products', ...) | Routes table با Patternهای Go 1.22 |
Form Request با rules() و validated() | dto.ProductWrite و Valid(ctx) یا Validator tag |
422 با {"message","errors":{"field":[...]} } | 422 از RFC 9457 با errors[] و JSON Pointer |
API Resource با toArray و whenLoaded | تابع Mapping به نام dto.View(p) |
Wrapperِ data، links، meta | ListView{data, next_cursor, has_more} و Header Link |
cursorPaginate(20) | Keyset در pgrepo.BuildList با Cursor رمزشده |
| Service container و Auto-wiring | Constructorهای فراخوانیشده در Run |
.env و config() | config.Load(getenv) |
php artisan serve، FPM | Run و http.Server و Shutdown |
| تولید OpenAPI با Package جامعه | Spec دستی با تست Drift یا oapi-codegen |
بدفهمیهای رایج (Misconceptions)
| باور | واقعیت |
|---|---|
| REST یعنی یک Endpoint برای هر جدول | Resource مفهوم کلاینت است؛ عمل دارای قاعده میتواند Sub-resource باشد |
200 با {"error": ...} کافی است اگر کلاینت Body را ببیند | Proxy، Retry library، SDK و Alert وضعیت را میخوانند؛ 4xx/5xx و RFC 9457 بدهید |
| کلاینت باید متن خطا را Parse کند | RFC 9457 میگوید consumers SHOULD NOT parse detail؛ برحسب type تصمیم بگیرید |
| Decode در Domain struct کد را کم میکند | انتساب انبوه (Mass assignment) و نشت جزئیات میسازد؛ DTO لازم است |
json.Decoder پیشفرض فیلد ناشناخته را رد میکند | فقط پس از DisallowUnknownFields()؛ بدنه هم تا MaxBytesReader نامحدود است |
| Validation و قاعدهٔ کسبوکار یکیاند | خطای شکل بدون I/O برابر 422؛ قاعدهٔ حالت در Service یا DB برابر 409 |
| Offset برای جدول کوچک کافی است | با تغییر داده بین صفحهها باز هم تکرار یا جاافتادگی دارد |
| Base64 یا Signature، Cursor را مبهم میکند | Base64 خواندنی است؛ امضا فقط دستکاری را میگیرد؛ AIP-158 Token غیرقابل Parse میخواهد، پس اینجا AES-GCM داریم |
PATCH باید Struct را بخواند و غیرصفرها را کپی کند | صفر و حذف را بیان نمیکند؛ RFC 7396 روی JSON و سپس Validation |
| Transaction جلوی Lost update را میگیرد | میان دو درخواست HTTP نه؛ ETag و If-Match و شرط Version لازماند |
Unique constraint، Retryِ POST را امن میکند | Retry را 409 میکند؛ Idempotency-Key پاسخ اول را Replay میکند |
| swag، OpenAPI 3 میسازد | نسخهٔ پایدار Swagger 2.0؛ 3.1 فقط در Release candidateهای v2 |
srv.Shutdown() همهچیز را تمام میکند | فقط منتظر اتصال فعال است؛ بدون Deadline تا ابد؛ ابتدا Readiness را خراب کنید |
| Liveness باید DB را بسنجد | قطعی DB همهٔ Podها را Restart میکند؛ وابستگی در Readiness بررسی شود |
| Go، DI container لازم دارد | Constructorها در یک Run با Compiler بررسی میشوند |
یادسپار (Cheat sheet)
| موضوع | به خاطر بسپارید |
|---|---|
| ابتدا برنامهریزی | Resource، URL، جدول عملیات و Status code؛ سپس openapi.json و بعد کد |
| مسیرها (Routes) | یک جدول؛ الگوی Go 1.22 با "METHOD /v1/products/{id}" و r.PathValue("id") |
| Handlerها | Maker function وابستگی میگیرد و http.Handler میدهد |
| Decode | Content-Type → MaxBytesReader → DisallowUnknownFields → یک مقدار → Valid(ctx) |
| خطا | application/problem+json، URI نوع، Status برابر در Header و Body، errors[] با Pointer |
| کدها | 400 خراب؛ 422 نامعتبر؛ 409 تعارض؛ 412 قدیمی؛ 428 بدون If-Match؛ 429 محدودشده |
| لایهها | Handler → Service مالک Repository → Repo؛ نگاشت Domain error در یک writeError |
| اتصال (Wiring) | main فقط Run(ctx, args, getenv, stdout) را میخواند؛ Constructor، بدون Global |
| پیکربندی (Config) | config.Load(getenv)؛ همهٔ خطاها با errors.Join |
| صفحهبندی (Pagination) | Keyset با (col, id)، limit+1، Token مبهم رمزشده وابسته به Filter/Sort و Link: rel="next" |
| Filter/Sort | پارامتر تایپدار؛ Sort مجاز به Column map؛ Index هر Sort |
PATCH | application/merge-patch+json؛ null حذف میکند؛ Array جایگزین؛ Validation دوباره |
| همزمانی (Concurrency) | ETag از Version؛ If-Match اجباری؛ WHERE version = ? |
| تکرار ایمن (Idempotency) | Idempotency-Key و Fingerprint بدنه؛ Replay؛ 409 در حال اجرا؛ 422 استفادهٔ متفاوت |
| نسخهبندی (Versioning) | /v1؛ نسخهٔ تازه فقط برای Breaking change؛ Deprecation و Sunset پیش از حذف |
| قرارداد (Contract) | OpenAPI 3.1 به شکل Embedded و Served؛ تست Routeها؛ Scalar یا Swagger UI در /docs |
| تست | httptest.NewServer با Repo حافظهای؛ Run به شکل End-to-end؛ t.Context() |
| خاموشی (Shutdown) | readyz با 503 → Drain delay → Shutdown(ctx with timeout) → انتظار ErrServerClosed |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا شکست Validation نباید با 200 و فیلد خطا برگردد، و این API چه وضعیت و بدنهای میدهد؟ حیاتی
پاسخ
پاسخ: کلاینت، Proxy، Retry library، SDK generator و Alert ابتدا Status code را میخوانند؛ 200 شکست را برای همه پنهان میکند. این API کد 422 با Content-Type: application/problem+json، یک URI در type برای Validation و آرایهٔ errors با JSON Pointer هر فیلد نامعتبر میدهد؛ قالب خطا را ببینید.
۲ — تفاوت 400، 422 و 409 در این API چیست؟ حیاتی
پاسخ
پاسخ: 400 یعنی بایتها به نوع درخواست تبدیل نشدهاند: JSON خراب، فیلد ناشناخته، نوع JSON غلط یا Query parameter نامعتبر. 422 یعنی Decode موفق بوده ولی مقدار، قاعدهٔ درخواست را نقض میکند؛ مثل قیمت منفی. 409 یعنی درخواست معتبر است اما با حالت ذخیرهشده تعارض دارد: SKU تکراری، فعال کردن محصول Archived یا Idempotency key که هنوز در حال اجراست.
۳ — چرا بهجای نوع Domain در DTO میخوانیم و DisallowUnknownFields چه اضافه میکند؟ حیاتی
پاسخ
پاسخ: DTO فقط فیلد قابل نوشتن کلاینت را دارد؛ بنابراین id و version از مسیر Mass assignment تنظیم نمیشوند و فیلد تازهٔ Domain به قرارداد نشت نمیکند. DisallowUnknownFields عضو غلطنوشته یا ممنوع را بهجای نادیده گرفتن با 400 رد میکند. ارسال فیلد فقطخواندنی در Merge patch هم با همین بررسی گرفته میشود.
۴ — چرا OFFSET پس از Insert یک ردیف را دوبار نشان میدهد و Keyset چگونه جلوی آن را میگیرد؟ حیاتی
پاسخ
پاسخ: OFFSET 20 یعنی بیست ردیف اول نتیجهٔ فعلی را رد کن. Insert در ابتدا همه را یک خانه عقب میبرد؛ ردیف بیستم صفحهٔ اول اکنون بیستویکم است و دوباره در صفحهٔ دوم میآید. Keyset با WHERE (sort_col, id) > (last_value, last_id) ردیفهای بعد از کلید دیدهشده را میخواهد و به تعداد ردیفهای قبل وابسته نیست؛ Index روی (sort_col, id) هر صفحه را به Seek تبدیل میکند.
۵ — چرا Cursor باید Tie-breaker داشته باشد و مبهم باشد؟ مهم
پاسخ
پاسخ: قیمت بهتنهایی ترتیب کامل نمیسازد؛ ردیفهای همقیمت ممکن است در مرز صفحه تکرار یا حذف شوند، پس id به Sort و Cursor اضافه میشود. Token مبهم ساختار داخلی را از قرارداد بیرون نگه میدارد و جلوی تغییر موقعیت را میگیرد؛ AIP-158 میگوید "must not be user-parseable". اینجا AES-GCM داریم چون Base64 و امضای تنها هنوز خواندنیاند؛ Token به Filter و Sort همان درخواست وابسته است؛ بنابراین اگر کلاینت آن را با Query متفاوتی بفرستد، سرور درخواست را با کد 400 رد میکند.
۶ — ETag و If-Match چگونه Lost update را میگیرند و چه وقت 412 یا 428 میدهیم؟ حیاتی
پاسخ
پاسخ: ETag نسخهٔ Resource را حمل میکند و Write باید آن را در If-Match پس بدهد. سرور فقط با تطابق نسخه در UPDATE ... WHERE version = ? مینویسد. Tag قدیمی 412 Precondition Failed و نبودن کامل Header، 428 Precondition Required از RFC 6585 میگیرد؛ کلاینت با حذف Header نمیتواند بررسی را دور بزند.
۷ — چرا PATCH بهجای Decode در Struct، RFC 7396 را روی سند JSON اعمال میکند؟ مهم
پاسخ
پاسخ: Struct معمولی غیبت، null و Zero value را از هم جدا نمیکند؛ در نتیجه روش کپی غیرصفرها قیمت 0 یا حذف فهرست را بیان نمیکند. Merge patch روی JSON کار میکند: عضو موجود تنظیم میشود، null حذف و عضو غایب حفظ میشود. سپس سند نهایی دقیقاً مثل PUT خوانده و اعتبارسنجی میشود تا یک مجموعه قاعده داشته باشیم.
۸ — کلاینت پس از Timeout در POST /v1/products دوباره تلاش میکند؛ چه چیزی Retry را امن میکند و حالتهای 409 و 422 کداماند؟ حیاتی
پاسخ
پاسخ: Headerِ Idempotency-Key باعث میشود سرور پاسخ نهایی نخست را زیر کلید ذخیره و برای همان بدنه با Status، Location و Body یکسان بازپخش کند. اگر درخواست نخست هنوز در حال اجرا باشد Retry کد 409 میگیرد. همان کلید با بدنهٔ متفاوت مطابق پیشنویس IETF، 422 میگیرد.
۹ — Run function pattern چیست و چرا تست را آسان میکند؟ مهم
پاسخ
پاسخ: main فقط Run(ctx, args, getenv, stdout) error را صدا میزند؛ این تابع وابستگیها را میسازد و تا لغو Context سرو میکند. چون سیستمعامل به شکل آرگومان وارد شده، تست برنامهٔ واقعی را در Goroutine با Env و Flag جعلی اجرا میکند، منتظر /readyz میماند و از HTTP استفاده میکند. سپس Context را Cancel میکند تا Graceful shutdown را هم، موازی با تستهای دیگر، بسنجد.
۱۰ — رابط Repository در Go کجا تعریف میشود و چرا برای هر Aggregate یک رابط داریم؟ مهم
پاسخ
پاسخ: در مصرفکننده، یعنی بستهٔ Service؛ سرویس نیاز دقیقش را بیان میکند و پیادهسازی به آن وابسته میشود. Interface per aggregate عملیات و خطای Domain را بیان میکند، مثل List با Keyset و Update با نسخهٔ مورد انتظار. Repository[T] عمومی Query building را به Service برمیگرداند و این عملیات را تمیز بیان نمیکند.
۱۱ — swaggo/swag، oapi-codegen و ogen را هرکدام در یک جمله مقایسه کنید؟ مهم
پاسخ
پاسخ: swaggo/swag، Code-first است و از Comment، Swagger 2.0 میسازد؛ OpenAPI 3.1 فقط در Release candidateهای v2 آن است. oapi-codegen، Spec-first است و از OpenAPI 3.0/3.1 رابط سرور، از جمله Strict server برای net/http و Routerهای رایج، Model و Client میسازد. ogen هم Spec-first است و حتی JSON encoding، Validation و Router را بدون Reflection تولید میکند.
۱۲ — Graceful shutdown پشت Load balancer را طوری توضیح دهید که درخواست از دست نرود؟ تکمیلی
پاسخ
پاسخ: با SIGTERM، /readyz را 503 کنید و Drain delay کافی بدهید تا Load balancer ترافیک تازه نفرستد. سپس srv.Shutdown را با Deadline صدا بزنید تا Listener بسته و درخواست جاری تمام شود؛ پیش از خروج منتظر http.ErrServerClosed از Serve بمانید. Liveness در تمام این مدت از وابستگیها مستقل میماند.
۱۳ — چرا برای JSON کردن 404 یک Handler فراگیر با مسیر "/" ثبت نمیکنیم؟ تکمیلی
پاسخ
پاسخ: Patternِ "/" با هر Path و Method تطبیق دارد؛ پس Method غلط روی مسیر موجود به آن میرسد و بهجای 405، کد 404 میگیرد و Headerِ Allow از دست میرود. Fallback ابتدا Pattern را از mux.Handler(r) میپرسد. فقط پاسخ 404/405 خود Mux را به Problem تبدیل میکند و Allow را نگه میدارد.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
| REST | سبک معماری Fielding: منبع، بازنمایی، پیام خودتوصیف و Hypermedia |
| منبع (Resource) | هر چیزی که کلاینت نام میدهد و با URL آدرسدهی میکند |
| مدلسازی منبع (Resource modelling) | انتخاب اسم، فیلد، چرخهٔ عمر و مالکیت در API |
| طراحی نشانی (URL design) | نام جمع مجموعه، ID مبهم، تودرتویی کم و پیشوند نسخه |
| برنامهریزی پروژه (Project planning) | نوشتن منبعها، URLها، عملیات و قواعد پیش از کد |
| بازنمایی (Representation) | JSON ارسالی یا دریافتی کلاینت برای Resource |
| رسیدگیکننده (Handler) | تابع تبدیل یک درخواست به یک پاسخ |
| تابع سازندهٔ Handler (Maker function) | وابستگی میگیرد و http.Handler میدهد |
| جدول مسیرها (Routes table) | فهرست همهٔ Patternها و Handlerها؛ سطح API |
الگوی ServeMux (Pattern) | Syntax مسیر در Go 1.22: "METHOD /path/{wildcard}" |
PathValue | متد دریافت مقدار Wildcard از مسیر Matchشده |
Request.Pattern | فیلد Go 1.23 با Pattern تطبیقیافته؛ مناسب Label متریک |
| شیء انتقال داده (DTO) | Data transfer object؛ Struct مخصوص Wire format |
| انتساب انبوه (Mass assignment) | نوشتن فیلد ممنوع از طریق Decode یا Update عمومی |
| اعتبارسنجی درخواست (Request validation) | بررسی مقدار پس از Decode؛ شکست برابر 422 |
| go-playground/validator | کتابخانهٔ Validation با Struct tag؛ Validator پیشفرض Gin |
Valid(ctx) | متد اعتبارسنجی دستی؛ رابط Validator در الگوی Mat Ryer |
| اشارهگر JSON (JSON Pointer) | مسیر RFC 6901 در سند، مثل /tags/2 |
| پوشش خطا (Error envelope) | شکل JSON مشترک همهٔ پاسخهای خطا |
| جزئیات خطا (Problem Details) | قالب RFC 9457 با application/problem+json |
about:blank | type پیشفرض؛ معنایی فراتر از Status code ندارد |
| عضو افزوده (Extension member) | فیلد اضافی تعریفشده توسط API مثل errors و request_id |
| کد وضعیت (Status code) | عدد سهرقمی HTTP برای رده و معنای نتیجه |
| 412 Precondition Failed | Header شرطی مثل If-Match تطبیق ندارد |
| 428 Precondition Required | سرور درخواست شرطی را لازم میداند؛ RFC 6585 |
| 422 Unprocessable Content | درخواست خوشساخت با محتوای نامعتبر؛ نام RFC 9110 |
الگوی مخزن (Repository pattern) | رابط شبیه Collection که Storage یک Aggregate را پنهان میکند |
| تجمیع (Aggregate) | گروه اشیای Domain که برای تغییر یک واحد محسوب میشوند |
| رابط بهازای تجمیع (Interface per aggregate) | Repository interface متناسب با Use caseهای یک Aggregate |
| لایهٔ سرویس (Service layer) | Use case و قواعد وابسته به حالت، مستقل از Transport |
| تزریق وابستگی با سازندهها (Dependency injection via constructors) | فرستادن همهٔ وابستگیها به New... |
| ریشهٔ ترکیب (Composition root) | یک محل ساخت همهٔ اشیای واقعی؛ Run |
| الگوی تابع اجرا (Run function pattern) | فراخوانی run(ctx, args, getenv, stdout) error از main؛ Mat Ryer |
| پیکربندی محیطی (Configuration via env) | قاعدهٔ Twelve-factor: تنظیم خاص Deploy از متغیر محیطی |
| صفحهبندی (Pagination) | بازگرداندن مجموعه در چند صفحه |
| صفحهبندی با جابهجایی (Offset pagination) | LIMIT n OFFSET k؛ رد کردن k ردیف |
| صفحهبندی با کلید (Keyset pagination) | WHERE (col, id) > (last)؛ ادامه پس از آخرین کلید دیدهشده |
| نشانگر (Cursor) | Token مبهم حاوی موقعیت صفحهٔ بعد |
next_cursor | فیلد پاسخ حامل Cursor صفحهٔ بعد |
| سرآیند پیوند (Link header) | Headerِ RFC 8288؛ اینجا URL صفحهٔ بعد با rel="next" |
| فیلتر کردن (Filtering) | محدود کردن Collection با Query parameter تایپدار |
| مرتبسازی (Sorting) | ترتیب برحسب فیلد مجاز؛ - برای نزولی |
PATCH | متد RFC 5789 برای اعمال مجموعهای از تغییرات به Resource |
| وصلهٔ ادغامی JSON (JSON Merge Patch) | قالب RFC 7396؛ null حذف و Array جایگزین میشود |
| وصلهٔ JSON (JSON Patch) | فهرست عملیات RFC 6902 مثل add، remove و replace |
برچسب موجودیت (ETag) | Entity tag؛ شناسهٔ نسخهٔ Representation |
If-Match | Header شرطی؛ Write فقط با تطابق ETag |
If-None-Match | Header شرطی؛ اگر ETag هنوز همان است 304 بده |
| مقایسهٔ قوی (Strong comparison) | تطبیق ETag که Weak tag را رد میکند؛ لازم برای If-Match |
| همزمانی خوشبینانه (Optimistic concurrency) | تشخیص Write متعارض با Version بهجای Lock |
| گم شدن ویرایش (Lost update) | Write یک کلاینت بیصدا کار دیگری را میپوشاند |
| کلید تکرار ایمن (Idempotency key) | کلید انتخابی کلاینت برای Retry ایمن درخواست غیر Idempotent |
| اثر انگشت (Fingerprint) | Hash بدنهٔ درخواست کنار Idempotency key |
| نسخهبندی (Versioning) | سرو همزمان قراردادهای ناسازگار، مثل /v1 و /v2 |
| Headerهای پایان عمر (Deprecation / Sunset headers) | اعلام بازنشستگی با RFC 9745 و RFC 8594 |
| OpenAPI 3.1 | قالب توصیف API همراستا با JSON Schema 2020-12 |
| Swagger 2.0 | پیش از OpenAPI 3؛ همچنان خروجی swaggo/swag v1 |
| swaggo/swag | Generatorِ Code-first برای سند Swagger از Commentهای Go |
| oapi-codegen | Generatorِ Spec-first برای سرور، Model و Client در Go |
| ogen | Generatorِ Spec-first با JSON، Validation و Router تولیدشده |
| سرور سختگیر (Strict server) | حالت oapi-codegen با شیء تایپدار درخواست و پاسخ |
| کلاینت تولیدشده (Generated client) | کد Client تایپدار حاصل سند OpenAPI |
| تست قرارداد (Contract test) | بررسی تطابق Routeهای در حال اجرا با Spec منتشرشده |
| Swagger UI | صفحهٔ تعاملی مرجع OpenAPI؛ swagger-ui-dist |
| Scalar | مرجع تعاملی OpenAPI که از یک HTML بار میشود |
| httptest | بستهٔ Go با NewServer و NewRecorder برای تست HTTP |
| تست سرتاسری (End-to-end test) | تست از زنجیرهٔ واقعی Handler یا کل برنامه |
| مخزن حافظهای (In-memory repository) | پیادهسازی Port مخزن با Map برای تست |
| خاموشی مرتب (Graceful shutdown) | توقف پذیرش، پایان درخواست جاری و سپس خروج |
| تأخیر تخلیه (Drain delay) | مکث میان خراب شدن Readiness و بستن Listener |
| زنده بودن / آمادگی (Liveness / readiness) | Health endpoint برای «Restart کنم؟» و «ترافیک بفرستم؟» |
| ثبت ساختیافته (Structured logging) | رکورد Log کلید/مقدار؛ JSON با log/slog |
| شناسهٔ درخواست (Request ID) | پیوند یک درخواست میان Logها و پاسخها |
| نقطهٔ اتصال محدودسازی نرخ (Rate limiting hook) | جای Middleware که میتواند با 429 رد کند |
| منابع API در Laravel (Laravel API Resources) | لایهٔ تبدیل Model به JSON در Laravel |
| درخواست فرم (Form Request) | کلاس Request در Laravel با rules() و authorize() |
منابع (References)
- Mat Ryer, "How I write HTTP services in Go after 13 years", Grafana Labs blog, 2024: https://grafana.com/blog/2024/02/09/how-i-write-http-services-in-go-after-13-years/
- Roy T. Fielding, "Architectural Styles and the Design of Network-based Software Architectures", 2000, chapter 5: https://ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
- RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457.txt
- RFC 7807, Problem Details (obsoleted): https://www.rfc-editor.org/rfc/rfc7807.txt
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110.txt
- RFC 5789, PATCH Method for HTTP: https://www.rfc-editor.org/rfc/rfc5789.txt
- RFC 7396, JSON Merge Patch: https://www.rfc-editor.org/rfc/rfc7396.txt
- RFC 6902, JSON Patch: https://www.rfc-editor.org/rfc/rfc6902.txt
- RFC 6901, JSON Pointer: https://www.rfc-editor.org/rfc/rfc6901.txt
- RFC 6585, Additional HTTP Status Codes (428, 429): https://www.rfc-editor.org/rfc/rfc6585.txt
- RFC 8288, Web Linking: https://www.rfc-editor.org/rfc/rfc8288.txt
- RFC 8594, The Sunset HTTP Header Field: https://www.rfc-editor.org/rfc/rfc8594.txt
- RFC 9745, The Deprecation HTTP Response Header Field: https://www.rfc-editor.org/rfc/rfc9745.txt
- RFC 9651, Structured Field Values for HTTP: https://www.rfc-editor.org/rfc/rfc9651.txt
- IETF draft, The Idempotency-Key HTTP Header Field: https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header
- IETF draft, RateLimit header fields for HTTP: https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers
- OpenAPI Specification 3.1.0: https://spec.openapis.org/oas/v3.1.0.html
- OpenAPI Specification 3.1.1: https://spec.openapis.org/oas/v3.1.1.html
- OpenAPI Specification 3.0.3: https://spec.openapis.org/oas/v3.0.3.html
- OpenAPI Specification, latest: https://spec.openapis.org/oas/latest.html
- swaggo/swag README: https://raw.githubusercontent.com/swaggo/swag/master/README.md
- swaggo/swag v2 README: https://raw.githubusercontent.com/swaggo/swag/v2/README.md
- swaggo/http-swagger README: https://raw.githubusercontent.com/swaggo/http-swagger/master/README.md
- oapi-codegen README: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/main/README.md
- oapi-codegen net/http server docs: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/main/docs/stdhttp-server.md
- ogen README: https://raw.githubusercontent.com/ogen-go/ogen/main/README.md
- kin-openapi README: https://raw.githubusercontent.com/getkin/kin-openapi/master/README.md
- huma README: https://raw.githubusercontent.com/danielgtaylor/huma/main/README.md
- go-playground/validator README: https://raw.githubusercontent.com/go-playground/validator/master/README.md
- go-playground/validator doc.go: https://raw.githubusercontent.com/go-playground/validator/master/doc.go
- pgx
PgError.SQLState: https://raw.githubusercontent.com/jackc/pgx/master/pgconn/errors.go - lib/pq
Error.SQLState: https://raw.githubusercontent.com/lib/pq/master/error.go - Google wire README: https://raw.githubusercontent.com/google/wire/main/README.md
- Uber fx README: https://raw.githubusercontent.com/uber-go/fx/master/README.md
- Uber fx
fxtest: https://raw.githubusercontent.com/uber-go/fx/master/fxtest/app.go - Uber dig README: https://raw.githubusercontent.com/uber-go/dig/master/README.md
- sqlc README: https://raw.githubusercontent.com/sqlc-dev/sqlc/main/README.md
- GORM README: https://raw.githubusercontent.com/go-gorm/gorm/master/README.md
- ent README: https://raw.githubusercontent.com/ent/ent/master/README.md
- caarlos0/env README: https://raw.githubusercontent.com/caarlos0/env/main/README.md
- kelseyhightower/envconfig README: https://raw.githubusercontent.com/kelseyhightower/envconfig/master/README.md
- evanphx/json-patch README: https://raw.githubusercontent.com/evanphx/json-patch/master/README.md
- Scalar: https://github.com/scalar/scalar
- Swagger UI README: https://raw.githubusercontent.com/swagger-api/swagger-ui/master/README.md
- Go module proxy, validator v10.30.1 go.mod: https://proxy.golang.org/github.com/go-playground/validator/v10/@v/v10.30.1.mod
- Go module proxy, oapi-codegen v2.9.0 go.mod: https://proxy.golang.org/github.com/oapi-codegen/oapi-codegen/v2/@v/v2.9.0.mod
- Go module proxy, ogen v1.25.0 go.mod: https://proxy.golang.org/github.com/ogen-go/ogen/@v/v1.25.0.mod
- Go module proxy, swag v2 versions: https://proxy.golang.org/github.com/swaggo/swag/v2/@v/list
- Go tutorial, "Developing a RESTful API with Go and Gin": https://go.dev/doc/tutorial/web-service-gin
- Go blog, "Routing Enhancements for Go 1.22": https://go.dev/blog/routing-enhancements
- Go 1.20 release notes (
errors.Join): https://go.dev/doc/go1.20 - Go 1.21 release notes: https://go.dev/doc/go1.21
- Go 1.22 release notes: https://go.dev/doc/go1.22
- Go 1.23 release notes: https://go.dev/doc/go1.23
- Go 1.24 release notes: https://go.dev/doc/go1.24
- Go 1.25 release notes: https://go.dev/doc/go1.25
- Go 1.26 release notes: https://go.dev/doc/go1.26
- Go 1.27 release notes: https://go.dev/doc/go1.27
net/httpserver source (Shutdown,ServeMux): https://go.dev/src/net/http/server.gonet/httprequest source (MaxBytesReader,PathValue): https://go.dev/src/net/http/request.gonet/httpstatus codes: https://go.dev/src/net/http/status.gonet/http/httptestserver: https://go.dev/src/net/http/httptest/server.goencoding/jsonstream (DisallowUnknownFields): https://go.dev/src/encoding/json/stream.goos/signal(NotifyContext): https://go.dev/src/os/signal/signal.go- Google AIP-122, Resource names: https://google.aip.dev/122
- Google AIP-132, Standard methods: List: https://google.aip.dev/132
- Google AIP-134, Standard methods: Update: https://google.aip.dev/134
- Google AIP-154, Resource freshness validation (etags): https://google.aip.dev/154
- Google AIP-158, Pagination: https://google.aip.dev/158
- Google AIP-160, Filtering: https://google.aip.dev/160
- Google AIP-185, API Versioning: https://google.aip.dev/185
- Google AIP-193, Errors: https://google.aip.dev/193
- Stripe API, Pagination: https://docs.stripe.com/api/pagination
- Stripe API, Idempotent requests: https://docs.stripe.com/api/idempotent_requests
- Stripe API, Errors: https://docs.stripe.com/api/errors
- Stripe API, Versioning: https://docs.stripe.com/api/versioning
- GitHub REST, Using pagination: https://docs.github.com/en/rest/using-the-rest-api/using-pagination-in-the-rest-api
- GitHub REST, API versions: https://docs.github.com/en/rest/about-the-rest-api/api-versions
- JSON:API specification: https://jsonapi.org/format/
- JSON:API cursor pagination profile: https://jsonapi.org/profiles/ethanresnick/cursor-pagination/
- Markus Winand, "No Offset": https://use-the-index-luke.com/no-offset
- PostgreSQL, Row and array comparisons: https://www.postgresql.org/docs/current/functions-comparisons.html
- PostgreSQL, LIMIT and OFFSET: https://www.postgresql.org/docs/current/queries-limit.html
- PostgreSQL, Multicolumn indexes: https://www.postgresql.org/docs/current/indexes-multicolumn.html
- The Twelve-Factor App, Config: https://12factor.net/config
- Kubernetes, Liveness, Readiness and Startup Probes: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
- Kubernetes, API health endpoints: https://kubernetes.io/docs/reference/using-api/health-checks/
- Laravel 13, Eloquent API Resources: https://laravel.com/docs/13.x/eloquent-resources
- Laravel 13, Validation: https://laravel.com/docs/13.x/validation
- Laravel 13, Pagination: https://laravel.com/docs/13.x/pagination
- Laravel 13, Controllers (
apiResource): https://laravel.com/docs/13.x/controllers