Go services · 3 MIN READ
Gin routes are adapters, not the whole application
Read route groups, path parameters and injected dependencies in a small Gin API.
Gin supplies routing, middleware and request/response helpers on top of net/http. It is useful when those conventions reduce repeated adapter code. It does not supply your domain model, persistence policy or downstream capacity, and a small API can also use the standard library.
Read the route from left to right
New creates an engine without the default middleware set. The group applies a common path prefix. A named segment is read from the Gin context, then handed to a service. This is an illustrative fragment: store and its result/error contract are application dependencies.
r := gin.New()
r.Use(gin.Logger(), gin.Recovery())
api := r.Group("/v1")
api.GET("/items/:id", func(c *gin.Context) {
id := c.Param("id")
item, err := store.Find(c.Request.Context(), id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "item unavailable"})
return
}
c.JSON(http.StatusOK, item)
})This simplified example treats Find failure uniformly. A real adapter should distinguish not-found from timeout, cancellation and internal failure rather than returning 404 for all of them.
Inject the dependency, not a global registry
Construct a handler with the interface it needs, then register methods on the engine. That makes a fake store available to tests and avoids hiding process configuration in globals. Keep route names and response shapes stable as an external contract.
Test routing without starting a server
A Gin engine implements http.Handler, so httptest can send an in-memory request through the router and middleware. Assert status, headers and body, including errors. The app includes local-preview patterns, but these reading examples are not a promise that every Gin version or native networking feature runs in its sandbox.
TAKE THIS WITH YOU
Use Gin to express the HTTP adapter. Keep application behavior behind explicit dependencies and test the adapter through its Handler interface.
Check your understanding
Which statement is correct about a gin route group?
Go to the source
Progress stays in this browser. No account needed.