Web frameworks · Intermediate · 24 min
Build a REST API in Go with Gin
By Padding · Updated 18 Nov 2026
Go 1.27.4 (golang:1.27 image) · Gin 1.12.0
You will build a versioned inventory API with Gin 1.12 on Go 1.27, with validated JSON input, request IDs, one error shape for every failure, release mode and tests, and know what Gin adds over the standard library router.
On this page
Gin is a Go web framework built around a fast router and a request context, *gin.Context, that carries helpers for reading input and writing responses. It became popular because it saved a lot of hand-written code before Go 1.22. Since then the standard library router matches methods and path wildcards on its own, so the honest question is no longer "how do I route?" but "is binding, validation and middleware plumbing worth a dependency?". You will build something real enough to answer that.
The API manages stock for a small shop: items with a SKU, a name, a quantity and a price. Prices are whole numbers of the smallest currency unit (cents, kobo or pesewas), which avoids floating-point rounding errors in money. You will put every route under /v1 so a future /v2 can live beside it, validate input with struct tags, tag every request with an ID that shows up in logs and error bodies, return the same error shape for every failure, switch Gin to release mode and test it all without opening a network port.
Items live in memory, so a restart empties them. That keeps the tutorial about Gin. The last step points to what to change for a database.
Step 1 · Create the module and add Gin
Make a throwaway folder, start a module and add Gin at an exact version:
mkdir -p ~/gin-inventory-demo
cd ~/gin-inventory-demo
go mod init example.com/inventory
go get github.com/gin-gonic/gin@v1.12.0go get records Gin in go.mod and its checksums in go.sum. The module name example.com/inventory only has to be unique on your machine because you are not publishing the code.
Check it worked
go list -m github.com/gin-gonic/ginThe command prints github.com/gin-gonic/gin v1.12.0.
Step 2 · Model the inventory
The store knows nothing about HTTP. It holds items in a map guarded by a mutex, because Go's HTTP server runs each request on its own goroutine and two requests may touch the map at once. It returns plain errors, ErrNotFound and ErrDuplicateSKU, that the HTTP layer will turn into status codes later. SKUs are compared without regard to case, so LAMP01 and lamp01 count as the same product:
cat > store.go <<'GO'
package main
import (
"errors"
"slices"
"strings"
"sync"
)
type Item struct {
ID int `json:"id"`
SKU string `json:"sku"`
Name string `json:"name"`
Quantity int `json:"quantity"`
PriceCents int `json:"price_cents"`
}
var (
ErrNotFound = errors.New("item not found")
ErrDuplicateSKU = errors.New("sku already in use")
)
type Store struct {
mu sync.Mutex
nextID int
items map[int]Item
}
func NewStore() *Store {
return &Store{nextID: 1, items: map[int]Item{}}
}
func (s *Store) List() []Item {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Item, 0, len(s.items))
for _, it := range s.items {
out = append(out, it)
}
slices.SortFunc(out, func(a, b Item) int { return a.ID - b.ID })
return out
}
func (s *Store) Get(id int) (Item, error) {
s.mu.Lock()
defer s.mu.Unlock()
it, ok := s.items[id]
if !ok {
return Item{}, ErrNotFound
}
return it, nil
}
func (s *Store) skuTaken(sku string, except int) bool {
for _, it := range s.items {
if it.ID != except && strings.EqualFold(it.SKU, sku) {
return true
}
}
return false
}
func (s *Store) Create(it Item) (Item, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.skuTaken(it.SKU, 0) {
return Item{}, ErrDuplicateSKU
}
it.ID = s.nextID
s.nextID++
s.items[it.ID] = it
return it, nil
}
func (s *Store) Update(it Item) (Item, error) {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.items[it.ID]; !ok {
return Item{}, ErrNotFound
}
if s.skuTaken(it.SKU, it.ID) {
return Item{}, ErrDuplicateSKU
}
s.items[it.ID] = it
return it, nil
}
func (s *Store) Delete(id int) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.items[id]; !ok {
return ErrNotFound
}
delete(s.items, id)
return nil
}
GO
go vet ./...Check it worked
go vet prints nothing and returns to the prompt. If it reports undefined or a syntax error, compare the file with the listing; a missing closing brace is the usual cause.
Step 3 · Give every response a request ID and one error shape
Clients should not have to guess what an error looks like. Every failure in this API returns the same body:
{"error":{"code":"not_found","message":"item not found","request_id":"G4762OSPMMNLUMKCJLQXKWNZXZ"}}code is a stable string a program can switch on, message is for people, and request_id ties the response to a line in the server log. Validation failures add a fields list. Small, predictable error bodies also help clients on slow or prepaid mobile connections, where every retry costs data.
errors.go holds two helpers. fail writes the error and calls AbortWithStatusJSON, which stops any handlers still waiting in the chain. bindJSON calls Gin's ShouldBindJSON, which decodes the body and then runs the validation rules from struct tags, and sorts the three ways it can fail: a rule broke (422), the body was too large (413), or the body was not valid JSON for the struct (400). Gin also has BindJSON, which writes a plain-text 400 by itself; the Should variant leaves the response to you, which is what keeps the shape consistent:
cat > errors.go <<'GO'
package main
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
type FieldError struct {
Field string `json:"field"`
Rule string `json:"rule"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
Fields []FieldError `json:"fields,omitempty"`
}
// fail ends the request with one error shape for every failure.
func fail(c *gin.Context, status int, code, message string, fields ...FieldError) {
c.AbortWithStatusJSON(status, gin.H{"error": APIError{
Code: code,
Message: message,
RequestID: c.GetString(requestIDKey),
Fields: fields,
}})
}
// bindJSON decodes and validates the body, or writes an error and returns false.
func bindJSON(c *gin.Context, dst any) bool {
err := c.ShouldBindJSON(dst)
if err == nil {
return true
}
var ve validator.ValidationErrors
if errors.As(err, &ve) {
fields := make([]FieldError, 0, len(ve))
for _, fe := range ve {
fields = append(fields, FieldError{Field: fe.Field(), Rule: fe.Tag()})
}
fail(c, http.StatusUnprocessableEntity, "validation_failed", "one or more fields are invalid", fields...)
return false
}
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
fail(c, http.StatusRequestEntityTooLarge, "body_too_large", "request body is over 1 MB")
return false
}
fail(c, http.StatusBadRequest, "invalid_json", "request body must be a JSON object")
return false
}
GOMiddleware in Gin is a gin.HandlerFunc like any handler. Code before c.Next() runs on the way in, code after it runs once the rest of the chain has finished, when the status code is known. RequestID keeps an X-Request-ID sent by a caller, such as a load balancer or another service, so one ID follows a request across systems. It only accepts up to 64 safe characters: a header copied into logs unchecked lets anyone write fake log lines. Anything else is replaced with rand.Text(), a random 26-character string from Go's crypto/rand. c.Set stores the ID on the context, where fail reads it back. LimitBody caps request bodies at 1 MB, because neither Gin nor net/http limits them by default:
cat > middleware.go <<'GO'
package main
import (
"crypto/rand"
"log/slog"
"net/http"
"regexp"
"time"
"github.com/gin-gonic/gin"
)
const requestIDKey = "requestID"
var validRequestID = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
// RequestID gives every request an ID, returns it in X-Request-ID and logs
// one line per request once the handlers have run.
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
id := c.GetHeader("X-Request-ID")
if !validRequestID.MatchString(id) {
id = rand.Text()
}
c.Set(requestIDKey, id)
c.Header("X-Request-ID", id)
start := time.Now()
c.Next()
slog.Info("request",
"id", id,
"method", c.Request.Method,
"path", c.Request.URL.Path,
"status", c.Writer.Status(),
"duration", time.Since(start).String(),
)
}
}
// LimitBody caps request bodies at 1 MB.
func LimitBody() gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<20)
c.Next()
}
}
GO
go vet ./...Check it worked
go vet prints nothing. If it reports a missing module for the validator, run go mod tidy; Gin already depends on that module, so it is already in your go.mod.
Step 4 · Group routes under /v1 and bind JSON
routes.go builds the router. A few choices are worth reading before you paste it:
gin.New()starts with no middleware.gin.Default()adds Gin's own logger and recovery, but hereRequestIDalready logs and the recovery should return the shared error shape, sogin.CustomRecoverydoes that.r.Group("/v1", LimitBody())makes a group with its own middleware.v1.Group("/items")nests inside it, soitems.GET("/:id", ...)servesGET /v1/items/:id.:idis a path parameter, read withc.Param("id").NoRouteandNoMethodreplace Gin's plain-text 404 and 405 responses.HandleMethodNotAllowedis off by default; without it aPATCHto an existing path returns 404 instead of 405.SetTrustedProxies(nil)tells Gin to trust no proxy headers, soc.ClientIP()cannot be spoofed withX-Forwarded-For. List your load balancer's addresses there when you have one.itemInputis the request body. Thebindingtags are rules for the validator Gin uses (go-playground/validator).QuantityandPriceCentsare pointers so thatrequiredmeans "present": on a plainint, a quantity of0would failrequired, and a missing quantity would look like0.- The
initfunction makes validation errors name fields as the JSON does (price_cents, notPriceCents), and turns onEnableDecoderDisallowUnknownFields, so a misspelt field such as"quantiy"is rejected instead of silently ignored. Both are global settings for every Gin engine in the program.
cat > routes.go <<'GO'
package main
import (
"errors"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
type itemInput struct {
SKU string `json:"sku" binding:"required,alphanum,min=3,max=20"`
Name string `json:"name" binding:"required,min=1,max=100"`
Quantity *int `json:"quantity" binding:"required,gte=0,lte=1000000"`
PriceCents *int `json:"price_cents" binding:"required,gte=0"`
}
func (in itemInput) toItem(id int) Item {
return Item{ID: id, SKU: in.SKU, Name: in.Name, Quantity: *in.Quantity, PriceCents: *in.PriceCents}
}
func init() {
// Report field names as they appear in the JSON, not the Go struct.
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterTagNameFunc(func(f reflect.StructField) string {
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if name == "" || name == "-" {
return f.Name
}
return name
})
}
// Reject bodies with fields the API does not know.
binding.EnableDecoderDisallowUnknownFields = true
}
func newRouter(store *Store) *gin.Engine {
r := gin.New()
r.HandleMethodNotAllowed = true
_ = r.SetTrustedProxies(nil)
r.Use(RequestID())
r.Use(gin.CustomRecovery(func(c *gin.Context, _ any) {
fail(c, http.StatusInternalServerError, "internal", "something went wrong")
}))
r.NoRoute(func(c *gin.Context) {
fail(c, http.StatusNotFound, "not_found", "no such route")
})
r.NoMethod(func(c *gin.Context) {
fail(c, http.StatusMethodNotAllowed, "method_not_allowed", "method not allowed on this route")
})
r.GET("/healthz", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
v1 := r.Group("/v1", LimitBody())
items := v1.Group("/items")
h := itemHandlers{store: store}
items.GET("", h.list)
items.POST("", h.create)
items.GET("/:id", h.get)
items.PUT("/:id", h.update)
items.DELETE("/:id", h.delete)
return r
}
type itemHandlers struct{ store *Store }
func itemID(c *gin.Context) (int, bool) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil || id < 1 {
fail(c, http.StatusBadRequest, "invalid_id", "id must be a positive whole number")
return 0, false
}
return id, true
}
func storeError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrNotFound):
fail(c, http.StatusNotFound, "not_found", "item not found")
case errors.Is(err, ErrDuplicateSKU):
fail(c, http.StatusConflict, "duplicate_sku", "another item already uses this sku")
default:
_ = c.Error(err)
fail(c, http.StatusInternalServerError, "internal", "something went wrong")
}
}
func (h itemHandlers) list(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"items": h.store.List()})
}
func (h itemHandlers) get(c *gin.Context) {
id, ok := itemID(c)
if !ok {
return
}
it, err := h.store.Get(id)
if err != nil {
storeError(c, err)
return
}
c.JSON(http.StatusOK, it)
}
func (h itemHandlers) create(c *gin.Context) {
var in itemInput
if !bindJSON(c, &in) {
return
}
it, err := h.store.Create(in.toItem(0))
if err != nil {
storeError(c, err)
return
}
c.Header("Location", fmt.Sprintf("/v1/items/%d", it.ID))
c.JSON(http.StatusCreated, it)
}
func (h itemHandlers) update(c *gin.Context) {
id, ok := itemID(c)
if !ok {
return
}
var in itemInput
if !bindJSON(c, &in) {
return
}
it, err := h.store.Update(in.toItem(id))
if err != nil {
storeError(c, err)
return
}
c.JSON(http.StatusOK, it)
}
func (h itemHandlers) delete(c *gin.Context) {
id, ok := itemID(c)
if !ok {
return
}
if err := h.store.Delete(id); err != nil {
storeError(c, err)
return
}
c.Status(http.StatusNoContent)
}
GOmain.go wraps the router in a standard http.Server. A *gin.Engine is an http.Handler, so you keep the server timeouts and graceful shutdown you would write without Gin, instead of calling r.Run(), which sets no timeouts. ADDR lets you change the listening address without editing code:
cat > main.go <<'GO'
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
addr := os.Getenv("ADDR")
if addr == "" {
addr = "127.0.0.1:8080"
}
srv := &http.Server{
Addr: addr,
Handler: newRouter(NewStore()),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
slog.Info("listening", "addr", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("server failed", "err", err)
os.Exit(1)
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown", "err", err)
}
slog.Info("stopped")
}
GO
go mod tidy
gofmt -l .
go vet ./...go mod tidy marks the validator module as a direct dependency, because your code now imports it.
Check it worked
gofmt -l . and go vet ./... both print nothing. grep validator go.mod shows github.com/go-playground/validator/v10 without an // indirect comment.
Step 5 · Run the API and create items
Build a binary and run it in the background, with its output going to server.log so you can read it afterwards. Building first matters: stopping go run does not always stop the program it started.
go build -o inventory .
./inventory > server.log 2>&1 &Give it a second, then create two items. -i shows the response headers, and --fail-with-body makes curl exit with an error on a 4xx or 5xx status while still printing the body:
curl -sS -i --fail-with-body -X POST http://127.0.0.1:8080/v1/items \
-H 'Content-Type: application/json' \
-d '{"sku":"LAMP01","name":"Solar lamp","quantity":12,"price_cents":4500}'
curl -sS --fail-with-body -X POST http://127.0.0.1:8080/v1/items \
-H 'Content-Type: application/json' \
-d '{"sku":"KETTLE2","name":"Electric kettle","quantity":0,"price_cents":12000}'
echoNow read, replace and list:
curl -sS --fail-with-body http://127.0.0.1:8080/v1/items/1
echo
curl -sS --fail-with-body -X PUT http://127.0.0.1:8080/v1/items/2 \
-H 'Content-Type: application/json' \
-d '{"sku":"KETTLE2","name":"Electric kettle","quantity":5,"price_cents":11500}'
echo
curl -sS --fail-with-body http://127.0.0.1:8080/v1/items
echo
cat server.logPUT replaces the whole item, so it takes the same body as POST. A partial update would be PATCH with its own input struct where every field is optional.
Check it worked
The first response starts with HTTP/1.1 201 Created and includes Location: /v1/items/1 and an X-Request-ID header, followed by the item with "id":1. Item 2 comes back with "quantity":5 after the PUT, and the list returns both items inside {"items":[...]}. server.log starts with Gin's debug output: a warning that it is running in debug mode, and one [GIN-debug] line per route, such as GET /v1/items/:id. Further down, each request has a line like INFO request id=... method=POST path=/v1/items status=201.
Step 6 · Send bad requests and read the errors
Each request below breaks a different rule. -w prints the status code after the body:
curl -sS -w ' %{http_code}\n' http://127.0.0.1:8080/v1/items/99
curl -sS -w ' %{http_code}\n' http://127.0.0.1:8080/v1/items/abc
curl -sS -w ' %{http_code}\n' -X POST http://127.0.0.1:8080/v1/items \
-H 'Content-Type: application/json' -d '{"sku":"a b","quantity":-3}'
curl -sS -w ' %{http_code}\n' -X POST http://127.0.0.1:8080/v1/items \
-H 'Content-Type: application/json' \
-d '{"sku":"lamp01","name":"Lamp","quantity":1,"price_cents":100}'
curl -sS -w ' %{http_code}\n' -X POST http://127.0.0.1:8080/v1/items \
-H 'Content-Type: application/json' \
-d '{"sku":"MUG3","name":"Mug","quantiy":4,"price_cents":800}'
curl -sS -w ' %{http_code}\n' -X PATCH http://127.0.0.1:8080/v1/items/1
curl -sS -w ' %{http_code}\n' -H 'X-Request-ID: order-7781' http://127.0.0.1:8080/v2/itemsThen stop the server with a TERM signal, the same signal a service manager sends on stop. Ctrl+C works too when the server runs in the foreground:
kill -TERM %1
wait
tail -n 2 server.logCheck it worked
The status codes, in order, are 404, 400, 422, 409, 400, 405 and 404, and every body has the same {"error":{...}} shape. The 422 body lists four fields: sku broke alphanum, name and price_cents broke required, and quantity broke gte. The duplicate SKU fails even though lamp01 is lower case. The misspelt quantiy is an invalid_json error rather than being ignored. The last response carries "request_id":"order-7781", the ID you sent. The log ends with INFO stopped.
Step 7 · Switch to release mode
Debug mode prints the route table and warnings, which helps while you build and clutters production logs. Gin reads the GIN_MODE environment variable when it starts, so you can switch without changing code. Run the same binary on another port with GIN_MODE=release:
GIN_MODE=release ADDR=127.0.0.1:8081 ./inventory > release.log 2>&1 &curl -sS --fail-with-body http://127.0.0.1:8081/healthz
echo
kill -TERM %1
wait
cat release.log
if grep -q GIN-debug release.log; then echo "still in debug mode"; false; fiOn a server, set GIN_MODE=release in the service's environment (a systemd Environment= line, or the environment settings of your Docker or Kubernetes deployment). To force it in code instead, call gin.SetMode(gin.ReleaseMode) before gin.New().
Check it worked
curl prints {"status":"ok"}. release.log has the listening, request and stopped lines from your own logger and no [GIN-debug] lines, and the final if prints nothing.
Step 8 · Test with httptest and gin.CreateTestContext
There are two useful levels of test. For routes, build the whole router with newRouter and send it requests through httptest.NewRecorder(), which records the response in memory; no port is opened. For a single piece of middleware, gin.CreateTestContext gives you a bare *gin.Context and an engine, so you can call the middleware function directly and inspect what it set. gin.SetMode(gin.TestMode) in TestMain hides the debug output:
cat > api_test.go <<'GO'
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestMain(m *testing.M) {
gin.SetMode(gin.TestMode)
m.Run()
}
func send(r http.Handler, method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestCreateThenGet(t *testing.T) {
r := newRouter(NewStore())
w := send(r, http.MethodPost, "/v1/items", `{"sku":"LAMP01","name":"Solar lamp","quantity":12,"price_cents":4500}`)
if w.Code != http.StatusCreated {
t.Fatalf("create: got %d, body %s", w.Code, w.Body)
}
if got := w.Header().Get("Location"); got != "/v1/items/1" {
t.Errorf("Location = %q", got)
}
w = send(r, http.MethodGet, "/v1/items/1", "")
var it Item
if err := json.Unmarshal(w.Body.Bytes(), &it); err != nil {
t.Fatal(err)
}
if it.Name != "Solar lamp" || it.Quantity != 12 {
t.Errorf("got %+v", it)
}
}
func TestErrorsShareOneShape(t *testing.T) {
r := newRouter(NewStore())
cases := []struct {
name, method, path, body string
status int
code string
}{
{"missing item", "GET", "/v1/items/99", "", 404, "not_found"},
{"bad id", "GET", "/v1/items/abc", "", 400, "invalid_id"},
{"broken json", "POST", "/v1/items", `{"sku":`, 400, "invalid_json"},
{"unknown field", "POST", "/v1/items", `{"sku":"A1B2","name":"x","quantity":1,"price_cents":1,"colour":"red"}`, 400, "invalid_json"},
{"negative quantity", "POST", "/v1/items", `{"sku":"A1B2","name":"x","quantity":-1,"price_cents":1}`, 422, "validation_failed"},
{"wrong method", "PATCH", "/v1/items/1", "", 405, "method_not_allowed"},
{"no route", "GET", "/v2/items", "", 404, "not_found"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
w := send(r, tc.method, tc.path, tc.body)
var body struct{ Error APIError }
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("not JSON: %s", w.Body)
}
if w.Code != tc.status || body.Error.Code != tc.code {
t.Errorf("got %d %q, want %d %q", w.Code, body.Error.Code, tc.status, tc.code)
}
if body.Error.RequestID == "" {
t.Error("request_id is empty")
}
})
}
}
func TestRequestIDMiddleware(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Request.Header.Set("X-Request-ID", "trace-42")
RequestID()(c)
if got := c.GetString(requestIDKey); got != "trace-42" {
t.Errorf("context id = %q", got)
}
if got := w.Header().Get("X-Request-ID"); got != "trace-42" {
t.Errorf("header id = %q", got)
}
}
func TestRequestIDReplacesUnsafeValues(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Request.Header.Set("X-Request-ID", "bad id\nwith newline")
RequestID()(c)
if got := c.GetString(requestIDKey); len(got) != 26 {
t.Errorf("expected a fresh 26-character id, got %q", got)
}
}
GO
go test ./...The table test is the one that protects your clients: if a future change returns plain text from some path, it fails.
Check it worked
go test prints ok example.com/inventory and a time. Change "not_found" in the "missing item" row to "missing" and run go test ./... again to see a failure naming the row; then change it back.
Step 9 · Weigh what Gin added, then clean up
Look back at what Gin did in this API and what the standard library would need instead. Since Go 1.22, http.ServeMux matches methods and wildcards, as in mux.HandleFunc("GET /v1/items/{id}", h) with r.PathValue("id"), and returns 405 for a wrong method by itself. So routing alone is no longer a reason to pick Gin. What Gin did give you here:
- Binding plus validation from struct tags. With the standard library you decode with
encoding/jsonand write the checks yourself, or add the same validator package directly. - Middleware that runs per group, with
c.Next()andAbortto control the chain. The standard library equivalent is wrapping handlers in functions, which works but has no built-in abort or per-request key-value store. NoRoute,NoMethodandCustomRecoveryhooks, which make the single error shape easy to enforce everywhere.c.JSON,c.Param,c.Setandc.GetString, which shorten handler code.
And what it costs:
go list -m all | wc -lThat count is every module in your build graph, including the ones Gin brings in for codecs and formats this API never uses; it was in the fifties when this tutorial was written. A standard-library version of this API has one: itself. Your handlers also take *gin.Context rather than http.ResponseWriter and *http.Request, so moving off Gin later means touching every handler. Global switches such as EnableDecoderDisallowUnknownFields and the validator's tag-name function apply to the whole program. A reasonable rule: a handful of routes with simple input suits the standard library; many routes with rich validation and per-group middleware is where Gin earns its place.
To keep the data, replace Store with a type backed by a database and keep the same method set; the handlers do not change. Pass c.Request.Context() to database calls so they stop when a client disconnects.
When you are done, remove the demo folder. Go and the module cache stay:
cd ~
rm -rf ~/gin-inventory-demoCheck it worked
go list -m all | wc -l printed a number well above 1. After the cleanup, ls ~/gin-inventory-demo reports that there is no such file or directory.
Next steps
- Build the same API with no dependencies and compare the code side by side: build a JSON API with Go's standard library router.
- Choose status codes and resource names deliberately: design REST endpoints: resources, methods and status codes.
- Move the error shape to a published standard: return API errors as problem details (RFC 9457).
- Review server basics such as timeouts and shutdown: write your first web server in Go.
Related tutorials
- Build a JSON API with Go's standard library routerYou will build a small inventory API in Go 1.27 with only the standard library: method and wildcard routes, strict JSON decoding, logging and panic-recovery middleware, a deadline on every request, a graceful shutdown on SIGTERM, and tests written with httptest.
- How to Write and Run Your First Web Server in GoYou will write a web server in Go 1.27 using only the standard library, with path routes, a JSON endpoint, a POST handler, timeouts and a clean shutdown, then test the handlers without opening a port and build the server into one binary.
- Hello World in Go: go mod init, go run and a single binaryYou will install Go 1.27, create a module, run Hello World with go run, build it into one self-contained binary, cross-compile a Windows .exe from Linux and add a --name flag with the flag package.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials