Gin foundations · 4 MIN READ
Your first Gin service: an engine, two routes and a test request
Build a Gin engine, register routes with a path parameter and exercise them without opening a port.
Gin is a router, a request context and a middleware chain built on top of net/http. A *gin.Engine is an ordinary http.Handler, so everything you know about http.Server, httptest and timeouts still applies. Start with a function that returns a configured engine: main can serve it, and a test can call it directly.
gin · A MAP OF THE IDEA
- Build engine
- Register routes
- Test via ServeHTTP
- Host in http.Server
Useful when
- Routing is testable in milliseconds without sockets.
- The middleware chain is explicit from the first line.
Watch out
- r.Run starts a server with no timeouts; prefer an explicit http.Server.
- Set gin.TestMode before building the engine to keep test output clean.
Implementation & operation cost: One constructor function and a test table; nothing beyond what a single-route service already needs.
What Gin adds to net/http
The standard library already parses requests, writes responses and runs servers. Gin adds a fast radix-tree router with named parameters, a *gin.Context that carries the request, the response writer and per-request values through a chain of handlers, plus helpers for binding input and rendering JSON. It does not replace http.Server: the engine is the Handler you give to one. Keeping that split in mind answers most questions about timeouts, TLS and shutdown later in the course.
Create the module and add Gin
A Gin service is an ordinary Go module. Create it with go mod init, add Gin at an explicit version with go get, and commit both go.mod and go.sum: the checksum file is what lets every later build prove that it downloaded the same Gin you reviewed. Pin the version deliberately and upgrade it on purpose after reading the release notes, rather than taking whatever happens to be newest on the day someone clones the repository.
mkdir notes-api && cd notes-api
go mod init example.com/notes-api
go get github.com/gin-gonic/gin@v1.12.0
# write main.go, then:
go run .
curl -i http://localhost:8080/healthgo get records gin v1.12.0 in go.mod and the hashes of Gin and its dependencies in go.sum. go run . builds and starts the package in the current directory. The curl line answers only once main hosts the engine in an http.Server, as shown later in this lesson. Run these commands in your own development environment; the first download needs access to the Go module proxy.
Build the engine and register routes
Put route registration in a function such as newRouter. It returns a fully configured *gin.Engine and has no side effects: no listening socket, no global state beyond Gin's mode. The example registers a fixed health route and a route with a :name parameter, then sends three requests through ServeHTTP and prints the status and body of each one.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/gin-gonic/gin"
)
func newRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Recovery())
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
r.GET("/hello/:name", func(c *gin.Context) {
c.String(http.StatusOK, "hello, %s", c.Param("name"))
})
return r
}
func main() {
gin.SetMode(gin.TestMode)
r := newRouter()
for _, path := range []string{"/health", "/hello/gopher", "/missing"} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
fmt.Println(w.Code, w.Body.String())
}
}gin.SetMode(gin.TestMode) runs before the engine is built, so Gin does not print its debug route table. ServeHTTP is the same method http.Server would call; httptest.NewRecorder captures the status and body. /health renders JSON, /hello/gopher binds "gopher" to :name, and /missing falls through to Gin's default 404 handler, which writes the plain body "404 page not found".
gin.Default versus gin.New
gin.Default() is gin.New() plus the Logger and Recovery middleware. That is convenient for a demo, but a service usually wants to choose its own access log format, fields and destination. Starting from gin.New() makes every piece of the chain visible in one place, which is also where a reviewer will look first when a request misbehaves.
r := gin.New()
// Recovery turns a handler panic into a 500 instead of killing the connection.
r.Use(gin.Recovery())
// Add your own structured access log here rather than relying on defaults.
r.Use(requestLogger(logger))This fragment is the explicit form of gin.Default(). Order matters: middleware registered with Use runs for every route added after it, in registration order. requestLogger is a placeholder for the slog-based middleware built later in this course.
Serve it with an explicit http.Server
r.Run(":8080") is a shortcut that calls http.ListenAndServe with no timeouts. A production process should construct an http.Server so that header, read, write and idle budgets are explicit and so that shutdown can drain in-flight requests. The engine stays exactly the same; only its host changes.
srv := &http.Server{
Addr: ":8080",
Handler: newRouter(),
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: time.Minute,
}
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}Run this fragment in your own development environment, not inside the app sandbox. ReadHeaderTimeout bounds slow clients that trickle headers; IdleTimeout closes unused keep-alive connections. http.ErrServerClosed is the normal result after Shutdown, so it is not treated as a failure.
Test before you listen
Because the router is just a Handler, the fastest feedback loop is a table of requests sent through ServeHTTP. That catches a wrong method, a missing slash or a route conflict in milliseconds, with no port allocation and no flaky network. Keep an integration test that starts a real server too, but let the in-process tests carry the bulk of routing and handler behaviour.
TAKE THIS WITH YOU
Return a configured *gin.Engine from a constructor, test it with httptest and ServeHTTP, and host it in an explicit http.Server rather than r.Run when it goes to production.
Check your understanding
Why can a Gin router be tested without opening a network port?
Go to the source
Progress stays in this browser. No account needed.