The most popular HTTP web framework in the Go ecosystem. A practice-focused guide covering routing, middleware, JSON binding, GORM, JWT authentication, and Docker deployment.
Intermediate
Updated Oct 10, 2026
~4 min read
10 sections
6 code examples
Web IDE lab included
🍸
Gin Web IDE
Run code in the browser with nothing to install and learn through step-by-step examples.
The most popular HTTP web framework in the Go ecosystem. A practice-focused guide covering routing, middleware, JSON binding, GORM, JWT authentication, and Docker deployment. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Backend / systems development
Before syntax, pin down the boundaries a request crosses: validation, processing, storage, and response.
REST API serversGORM ORMJWT authenticationHigh-performance microservices
Architecture diagrams
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Gin.
Learning flow
Rendering diagram…
Architecture view
Rendering diagram…
What is Gin?
When you first open Gin, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
Gin is a high-performance HTTP web framework written in Go. Built on HttpRouter, it can handle hundreds of thousands of requests per second.
Routing
Here you look at Routing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
gin.Default() returns a router with the logging and panic recovery middleware already applied, so it is ready for real work with no extra setup. Grouping a common prefix (/api/v1/users) with Group saves writing it on every path and makes it easy to organize routes by version or resource.
Here you look at Request binding & validation alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Once binding rules are declared in the struct tags, a single ShouldBindJSON call does both the JSON parsing and the required-field and format validation. When a rule such as required, email, or min=8 is not met, err holds the reason validation failed, so there is no need to write validation logic by hand with if statements in every handler.
GO
type CreateUserRequest struct { Name string `json:"name" binding:"required,min=2"` Email string `json:"email" binding:"required,email"` Password string `json:"password" binding:"required,min=8"`}func createUser(c *gin.Context) { var req CreateUserRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // handling logic c.JSON(http.StatusCreated, user)}
Middleware
Here you look at Middleware alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Middleware is a function that slots common logic (logging, authentication, panic recovery, CORS) in before and after a request reaches the actual handler. Calling `c.Next()` moves on to the next middleware (or handler) in the chain, and putting code before and after it lets you implement both pre-request and post-response handling.
middleware.goGO
func RequestLogger() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Next() // run the next middleware/handler — the response is produced here log.Printf("%s %s %d %v", c.Request.Method, c.Request.URL.Path, c.Writer.Status(), time.Since(start)) }}func AuthRequired() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("Authorization") if token == "" { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"}) return // after Abort, if c.Next() is not called, later handlers do not run } c.Next() }}r := gin.New()r.Use(gin.Recovery(), RequestLogger()) // global middlewareprotected := r.Group("/api/v1/admin")protected.Use(AuthRequired()) // applied to the group only
GORM + database
Here you look at GORM + database alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
GORM is the most widely used ORM in the Go ecosystem; you define the table schema with struct tags and sync the actual tables with `AutoMigrate`. Inside a Gin handler, the `*gorm.DB` that GORM returns is used directly as a query builder.
model.goGO
type User struct { ID uint `gorm:"primaryKey"` Name string `gorm:"not null"` Email string `gorm:"uniqueIndex;not null"` CreatedAt time.Time}db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})if err != nil { log.Fatal(err)}db.AutoMigrate(&User{}) // create the table/sync columns from the structfunc getUser(c *gin.Context) { var user User if err := db.First(&user, c.Param("id")).Error; err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "user not found"}) return } c.JSON(http.StatusOK, user)}func createUser(c *gin.Context) { var user User c.ShouldBindJSON(&user) db.Create(&user) c.JSON(http.StatusCreated, user)}
JWT authentication
Here you look at JWT authentication alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
With the golang-jwt library, a signed token is issued on successful login, and later requests are identified by verifying that token in middleware. The verified user information is put into the context with `c.Set` and taken out in later handlers.
Here you look at Docker deployment alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Go compiles to a static binary, so the runtime-stage image does not need a whole OS or runtime. Building a pure static binary with CGO_ENABLED=0 lets it run with just that one binary on top of scratch (the empty image), bringing the final image size down to a few MB.
DOCKERFILE
FROM golang:1.22-alpine AS builderWORKDIR /srcCOPY go.mod go.sum ./RUN go mod downloadCOPY . .RUN CGO_ENABLED=0 go build -ldflags="-w -s" -o /app ./cmd/serverFROM scratchCOPY --from=builder /app /appCOPY --from=builder /etc/ssl/certs /etc/ssl/certsEXPOSE 8080ENTRYPOINT ["/app"]
Gin practical design
Gin practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
With Gin, make the middleware order and the responsibility for request binding/validation clear. It is important not to put business logic in handlers.
Decision point
Question to ask
Practical guideline
Boundaries
Which parts of the Gin code are most likely to change?
Separate input/output, configuration, external integrations, and the core rules.
State
Where is state created and where does it go away?
Make the owner and lifecycle of state visible in the code.
Failure
What does the caller receive on failure?
Decide the timeout, fallback, and error contract first.
Gin operating standards
This section covers Gin operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.
In operation you need panic recovery, structured logging, a request id, timeout middleware, and a payload size limit.
Gin verification strategy
Gin verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Verify routes, middleware, validation errors, and auth failures with httptest.
Quality axis
How to verify
Definition of done
Correctness
Automate the normal/failure cases.
The core scenarios pass reproducibly.
Regression prevention
When fixing a bug, leave the same case behind as a test.
The same failure is not deployed again.
Operability
Check the logs, metrics, and alerts.
There is a path for tracing the cause when a problem occurs.
Gin: frequently asked questions
Do I have to use a web framework in Go?
You can build a server with net/http from the standard library alone. A framework such as Gin makes routing, request binding and validation, and middleware composition concise, which helps more as the number of APIs grows. For a small service, starting with the standard library is enough.
How do I validate request data in Gin?
Write binding tags on struct fields to state what is required and in what format, then load the request body into the struct with ShouldBindJSON. It returns an error when a condition is not met, and you return that as a 400 response.
What is middleware used for?
It holds work common to requests that runs before and after handlers. Request logging, authentication checks, panic recovery, and CORS handling are typical. It can be applied globally or only to a specific route group.