GO
Building a Statistical Reporting API with Go and Gin
Introduction
Gin is one of the most widely used HTTP frameworks for Go. It handles routing, request parameters and JSON responses, and it stays close to Go's own net/http package: a Gin handler is still an ordinary function, and a Gin router is still an http.Handler underneath. That closeness makes it easy to see exactly what the framework adds.
Teams that skip a framework tend to end up with handlers that mix URL parsing, validation and response formatting in one function, each written slightly differently. That works for one endpoint and becomes hard to maintain at ten. In this tutorial we will build a statistical reporting API with mock data for user activity, sales and system performance. Along the way we will use Gin's router, route groups, query and path parameters, and one consistent JSON envelope for every response.
A few assumptions so that every command and path is exact:
- You are working in the Go sandbox on Bytestark.com, and your starting folder is
/home/coder/learning. - That folder already is a Go module: its
go.modstarts withmodule learningand listsgithub.com/gin-gonic/gin, whose code is vendored invendor/. You do not needgo mod initor any download; packages we create underapi/are imported aslearning/api/.... - You will open the API on your sandbox URL and use
curlfrom a second terminal to see exact responses.
Background
Gin is an HTTP framework for Go. gin.Default() returns a router (Gin calls it an engine) with two middleware already attached: Logger, which prints one line per request, and Recovery, which turns a panic inside a handler into a 500 response instead of crashing the server. A middleware is a function that runs before (and after) the handler for every request it is attached to.
*gin.Context is the single argument every Gin handler receives. It wraps the incoming request and the response writer and offers helpers to read parameters (c.Query, c.DefaultQuery, c.Param) and to write a response (c.JSON).
A route group is a set of routes that share a URL prefix and, optionally, middleware. A group created with /api/v1 gives every route registered on it that prefix.
Struct tags are strings attached to struct fields that other packages can read. encoding/json reads the json:"..." tag: a field declared as TotalUsers int with the tag json:"total_users" is written as "total_users" in JSON.
gin.H is Gin's name for map[string]any, a quick way to build a JSON object without declaring a struct.
Practical Scenario
A business intelligence team feeds an internal dashboard with operational metrics: user activity counts, sales by period and live system health. The numbers come from several backends, but the dashboard needs one HTTP API that answers quickly with predictable JSON.
The first version was a single main.go with net/http handlers. Each handler parsed its query string by hand and encoded JSON its own way. When something went wrong it wrote a plain-text message, so the dashboard had to cope with a different response shape from every endpoint. Adding a version prefix meant editing every path.
The requirements kept growing: per-user breakdowns, sales filtered by period with a clear error for a bad period, and a health endpoint the infrastructure team can probe. Each of these is a small feature, but on the hand-rolled base every one of them adds more duplicated code.
The Problem
Let's start from the hand-rolled version: one net/http handler that serves sales figures for a period. Watch what it does with a period it should not accept, and what an error looks like.
Create the file:
touch main.go
Put this code in it:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func statsHandler(w http.ResponseWriter, r *http.Request) {
period := r.URL.Query().Get("period")
if period == "" {
period = "monthly"
}
data := map[string]interface{}{
"period": period,
"total_sales": 87543.21,
"total_orders": 543,
}
b, err := json.Marshal(data)
if err != nil {
fmt.Fprintf(w, "error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
func main() {
http.HandleFunc("/stats", statsHandler)
http.ListenAndServe(":9000", nil)
}
Run it:
go run main.go
The command prints nothing: http.ListenAndServe blocks and serves until you stop it with Ctrl+C. Leave it running and, from a second terminal, request the endpoint three ways:
curl -s http://127.0.0.1:9000/stats; echo
curl -s "http://127.0.0.1:9000/stats?period=quarterly-ish"; echo
curl -s http://127.0.0.1:9000/nothing
{"period":"monthly","total_orders":543,"total_sales":87543.21}
{"period":"quarterly-ish","total_orders":543,"total_sales":87543.21}
404 page not found
First, the address. http.ListenAndServe(":9000", nil) has an empty host before the colon, which in Go means "listen on every network interface". That matters in the sandbox: your sandbox has a public URL of the form https://webserver-p9000-<id1>-<id2>.bytestark.com (the two ids were shown when the sandbox launched), which reaches your program from outside the sandbox's loopback interface and only on port 9000. A server bound to 127.0.0.1 would be invisible to that URL. Open /stats on your sandbox URL and the browser shows the same JSON as the first curl.
Now the handler, line by line:
r.URL.Query().Get("period")returns the value ofperiod, or""when it is missing, so theifsupplies the default"monthly"by hand.map[string]interface{}holds the response.json.Marshalwrites map keys in sorted order, which is whyperiodcomes beforetotal_ordersin the output.w.Header().Set("Content-Type", "application/json")has to be remembered in every handler; forget it and the client is told it received plain text.http.HandleFunc("/stats", statsHandler)registers the handler on Go's default router, which is what thenilinListenAndServeselects.
The output shows the problems the scenario describes. quarterly-ish was accepted and echoed back as if it were a real period, because nothing validates it. The error for an unknown URL is the plain text 404 page not found, not JSON. And the fmt.Fprintf(w, "error: %v", err) branch would send yet another shape, plain text with status 200, because nothing sets an error status. A dashboard that calls this API cannot rely on any single response format.
Try it: Delete the w.Header().Set(...) line, restart with go run main.go, and run curl -s -i http://127.0.0.1:9000/stats | grep Content-Type. Predict the header before you look. It is Content-Type: text/plain; charset=utf-8: when a handler does not set the type, net/http sniffs the first bytes of the body, and a { does not look like any known format, so it falls back to plain text. Put the line back.
A health check with Gin
The first endpoint the infrastructure team asked for is a health check. It is also the smallest possible Gin program, so it shows what the framework adds before any of our own structure. Replace the entire content of main.go with:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "healthy",
"message": "API is running",
})
})
router.Run(":9000")
}
Stop the previous server with Ctrl+C and start this one:
go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /health --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :9000
Unlike net/http, Gin tells you what it built. The startup lines, one at a time:
- The first warning confirms what
gin.Default()did: it attached Logger and Recovery.gin.New()would give you an engine with no middleware at all. - Debug mode is the default and is what prints these
[GIN-debug]lines; release mode silences them. GET /health --> main.main.func1 (3 handlers)is the route table.main.main.func1is Go's name for the first anonymous function insidemain()in packagemain, our handler.3 handlersis the chain a request to/healthpasses through: Logger, Recovery, then our function.- The proxy warning is about
c.ClientIP(): by default Gin believes anX-Forwarded-Forheader from any sender. We never read the client IP, so it does not affect this API; a real deployment callsrouter.SetTrustedProxies(...)with its load balancer's addresses. Listening and serving HTTP on :9000isrouter.Run(":9000"). It is the same empty-host rule as before: every interface, port 9000.
From the second terminal:
curl -s http://127.0.0.1:9000/health; echo
curl -s -i http://127.0.0.1:9000/health | grep Content-Type
{"message":"API is running","status":"healthy"}
Content-Type: application/json; charset=utf-8
The server terminal now shows one line per request, written by the Logger middleware:
[GIN] 2026/11/15 - 08:02:20 | 200 | 1.15ms | 127.0.0.1 | GET "/health"
Read left to right: the time the request finished, the status code, how long the handler chain took, the client address, the method and the path. Your times will differ.
c.JSON(http.StatusOK, gin.H{...}) did three things that took three separate lines in The Problem: it wrote the status code 200, set Content-Type: application/json; charset=utf-8, and encoded the map. Because gin.H is a map, the keys again come out sorted: message before status. Open /health on your sandbox URL to see the same object in the browser.
Try it: Request a path that does not exist, curl -s -i http://127.0.0.1:9000/nothing | head -1, and predict the status and which middleware logs it. It is HTTP/1.1 404 Not Found, and the Logger still prints a 404 line for it, because Gin runs the engine's global middleware even when no route matches.
Models and a handler struct
The dashboard needs typed data with fixed field names, and handlers that can later be given a database or a cache without changing their signatures. We will put the data shapes in one package and the HTTP handlers in another, with main.go connecting them.
Create the two package folders:
mkdir -p api/models api/handlers
Create api/models/stats.go:
package models
import "time"
type UserStats struct {
TotalUsers int `json:"total_users"`
ActiveUsers int `json:"active_users"`
NewUsers int `json:"new_users"`
Timestamp time.Time `json:"timestamp"`
}
type SalesReport struct {
Period string `json:"period"`
TotalSales float64 `json:"total_sales"`
TotalOrders int `json:"total_orders"`
AverageOrder float64 `json:"average_order"`
TopProduct string `json:"top_product"`
}
type PerformanceMetrics struct {
CPUUsage float64 `json:"cpu_usage"`
MemoryUsage float64 `json:"memory_usage"`
RequestsPerSec int `json:"requests_per_sec"`
AvgResponseTime float64 `json:"avg_response_time_ms"`
}
Create api/handlers/handlers.go:
package handlers
import (
"math/rand"
"net/http"
"time"
"learning/api/models"
"github.com/gin-gonic/gin"
)
type StatsHandler struct{}
func NewStatsHandler() *StatsHandler {
return &StatsHandler{}
}
func (h *StatsHandler) GetUserStats(c *gin.Context) {
stats := models.UserStats{
TotalUsers: rand.Intn(10000) + 5000,
ActiveUsers: rand.Intn(3000) + 1000,
NewUsers: rand.Intn(500) + 100,
Timestamp: time.Now(),
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": stats,
})
}
Replace main.go with a version that creates the handler and registers its first route inside a group:
package main
import (
"net/http"
"learning/api/handlers"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
statsHandler := handlers.NewStatsHandler()
router.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "healthy",
"message": "API is running",
})
})
v1 := router.Group("/api/v1")
{
stats := v1.Group("/stats")
{
stats.GET("/users", statsHandler.GetUserStats)
}
}
router.Run(":9000")
}
Restart the server and request the new endpoint:
curl -s http://127.0.0.1:9000/api/v1/stats/users; echo
{"data":{"total_users":11760,"active_users":1814,"new_users":367,"timestamp":"2026-11-15T08:02:34.072068254Z"},"success":true}
The numbers come from rand.Intn and the timestamp from time.Now(), so yours will differ on every request; the field names and their order will not. The route table at startup now contains GET /api/v1/stats/users --> learning/api/handlers.(*StatsHandler).GetUserStats-fm (3 handlers); the -fm suffix is how Go names a method value, a method already bound to its receiver, statsHandler.
The models file is only type declarations. Each field's json:"..." tag is the name it gets in the response, which is why TotalUsers became total_users. time.Time is written as an RFC 3339 string, 2026-11-15T08:02:34...Z, the format JavaScript's Date parses directly.
The handler file, part by part:
"learning/api/models"is the import path of the models package: the module name fromgo.mod, then the folder. That is why nogo modcommand was needed.type StatsHandler struct{}is empty today. Its purpose is to be the place where dependencies will live. A real handler would hold a*sql.DBor a cache client as fields, and every method could use them throughh.NewStatsHandler()is a constructor, a plain function that returns a ready-to-use value. It is where those dependencies would be passed in, somain.gois the only place that decides which database the handlers use.func (h *StatsHandler) GetUserStats(c *gin.Context)is a method with the exact signature Gin expects of a handler, sostatsHandler.GetUserStatscan be passed straight tostats.GET(...).- The response is
gin.H{"success": true, "data": stats}. Every endpoint in this API answers with the same two keys,successand then eitherdataorerror, so the dashboard has one parsing path. Notice the two orders in the output: the outer object is a map, so its keys are sorted (databeforesuccess), while the inner object is a struct, whose fields are written in declaration order.
In main.go, router.Group("/api/v1") returns a group whose routes all start with /api/v1, and v1.Group("/stats") nests a second prefix inside it, so stats.GET("/users", ...) registers /api/v1/stats/users. The curly braces after each Group call are an ordinary Go block: they change nothing for the compiler, but they make the nesting of the URL visible in the code.
Try it: Change v1 := router.Group("/api/v1") to router.Group("/api/v2"), restart, and predict which of /api/v1/stats/users and /api/v2/stats/users answers. Only v2 does, and you changed one string: every route registered on the group gets its prefix from that one place. Change it back.
Route groups catch a missing handler at compile time
The dashboard also wants sales and performance figures. Let's register both routes in the group first, before writing the handlers, and see what Go makes of it. In main.go, add two lines under the /users route:
stats.GET("/users", statsHandler.GetUserStats)
stats.GET("/sales", statsHandler.GetSalesReport)
stats.GET("/performance", statsHandler.GetPerformanceMetrics)
Stop the server and run it again:
go run main.go
# command-line-arguments
./main.go:27:37: statsHandler.GetSalesReport undefined (type *handlers.StatsHandler has no field or method GetSalesReport)
./main.go:28:43: statsHandler.GetPerformanceMetrics undefined (type *handlers.StatsHandler has no field or method GetPerformanceMetrics)
The program does not start at all. # command-line-arguments is the name Go gives the package built from files listed on the command line, here main.go. Each error line gives the file, line and column, then the reason: the type *handlers.StatsHandler has no method with that name. Because routes are registered with method values rather than with strings, a route that points at a handler that does not exist is a compile error, and it can never become a 404 in production.
Now add both handlers to the end of api/handlers/handlers.go:
func (h *StatsHandler) GetSalesReport(c *gin.Context) {
period := c.DefaultQuery("period", "monthly")
validPeriods := map[string]bool{
"daily": true,
"weekly": true,
"monthly": true,
"yearly": true,
}
if !validPeriods[period] {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": "Invalid period. Use: daily, weekly, monthly, or yearly",
})
return
}
totalSales := rand.Float64() * 100000
totalOrders := rand.Intn(1000) + 100
report := models.SalesReport{
Period: period,
TotalSales: totalSales,
TotalOrders: totalOrders,
AverageOrder: totalSales / float64(totalOrders),
TopProduct: "Product-" + string(rune(rand.Intn(26)+65)),
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": report,
})
}
func (h *StatsHandler) GetPerformanceMetrics(c *gin.Context) {
metrics := models.PerformanceMetrics{
CPUUsage: rand.Float64() * 100,
MemoryUsage: rand.Float64() * 100,
RequestsPerSec: rand.Intn(1000) + 100,
AvgResponseTime: rand.Float64() * 100,
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": metrics,
})
}
Run go run main.go again; it compiles and the route table lists /sales and /performance. Request the sales report three ways and the performance metrics once:
curl -s "http://127.0.0.1:9000/api/v1/stats/sales?period=weekly"; echo
curl -s "http://127.0.0.1:9000/api/v1/stats/sales"; echo
curl -s -i "http://127.0.0.1:9000/api/v1/stats/sales?period=invalid" | grep -E '^HTTP|^\{'
curl -s http://127.0.0.1:9000/api/v1/stats/performance; echo
{"data":{"period":"weekly","total_sales":65456.01177413129,"total_orders":350,"average_order":187.017176497518,"top_product":"Product-Y"},"success":true}
{"data":{"period":"monthly","total_sales":10799.406948291766,"total_orders":500,"average_order":21.598813896583533,"top_product":"Product-D"},"success":true}
HTTP/1.1 400 Bad Request
{"error":"Invalid period. Use: daily, weekly, monthly, or yearly","success":false}
{"data":{"cpu_usage":64.52844791429789,"memory_usage":8.267344916044786,"requests_per_sec":979,"avg_response_time_ms":71.81264574056421},"success":true}
Again the figures are random and yours will differ. The shapes and the status codes will not.
GetSalesReport, part by part:
c.DefaultQuery("period", "monthly")returns theperiodquery parameter, or"monthly"when it is absent. It replaces theGetplusif period == ""pair from The Problem, and it is why the second request reportsmonthly.c.Query("period")would return""instead.validPeriodsis amap[string]boolused as a set. Looking up a key that is not in the map returns the zero value ofbool,false, so!validPeriods[period]is true for anything outside the four periods, includinginvalidandquarterly-ish.- On failure,
c.JSON(http.StatusBadRequest, ...)sends status400with the same envelope as a success,successset tofalseand anerrormessage. Thereturnafter it matters:c.JSONwrites the response but does not stop the function, and withoutreturnthe handler would carry on and try to write a second response. totalSales / float64(totalOrders)converts theinttofloat64first, because Go does not divide afloat64by anint.string(rune(rand.Intn(26) + 65))picks a letter: 65 is the code ofA, so the result is one ofAtoZ. Theruneconversion is what makesstringproduce a character;stringof a plainintis flagged bygo vetfor exactly this confusion.
GetPerformanceMetrics follows the same envelope. Its JSON key avg_response_time_ms differs from the Go field name AvgResponseTime, which shows that the tag, not the field name, is the API contract: the Go code can be renamed without breaking the dashboard.
Try it: Remove the return after the 400 response in GetSalesReport, restart, and request ?period=invalid with curl -s -i. Predict the status code and the body. The status stays 400, because the first write fixed it, but the body now contains two JSON objects back to back, the error and then a report with "period":"invalid", which no JSON parser will accept. The server terminal also prints [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 200: the second c.JSON tried to set a status after the first had already sent it. Put the return back.
Path parameters for one user
The dashboard also needs figures for a single user, addressed as /api/v1/stats/user/12345. The id is part of the path, so it is a path parameter, not a query parameter: it identifies which resource you want, while query parameters such as period adjust how it is reported.
Add this handler to the end of api/handlers/handlers.go:
func (h *StatsHandler) GetUserStatsByID(c *gin.Context) {
userID := c.Param("id")
stats := gin.H{
"user_id": userID,
"total_orders": rand.Intn(100),
"total_spent": rand.Float64() * 1000,
"account_age_days": rand.Intn(365),
"last_login": time.Now().Add(-time.Duration(rand.Intn(24)) * time.Hour),
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": stats,
})
}
And register it in main.go, under the /users route:
stats.GET("/user/:id", statsHandler.GetUserStatsByID)
Here is the complete main.go at this point:
package main
import (
"net/http"
"learning/api/handlers"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
statsHandler := handlers.NewStatsHandler()
router.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "healthy",
"message": "API is running",
})
})
v1 := router.Group("/api/v1")
{
stats := v1.Group("/stats")
{
stats.GET("/users", statsHandler.GetUserStats)
stats.GET("/user/:id", statsHandler.GetUserStatsByID)
stats.GET("/sales", statsHandler.GetSalesReport)
stats.GET("/performance", statsHandler.GetPerformanceMetrics)
}
}
router.Run(":9000")
}
Restart the server and request one user, then the path with no id:
curl -s http://127.0.0.1:9000/api/v1/stats/user/12345; echo
curl -s -i http://127.0.0.1:9000/api/v1/stats/user/ | grep -E '^HTTP|^Location'
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:9000/api/v1/stats/user
{"data":{"account_age_days":40,"last_login":"2026-11-14T20:03:00.552470544Z","total_orders":76,"total_spent":898.6322428069655,"user_id":"12345"},"success":true}
HTTP/1.1 301 Moved Permanently
Location: /api/v1/stats/user
404
In the route "/user/:id", the segment starting with a colon is a named parameter: it matches any one non-empty path segment, and c.Param("id") returns what was there, here "12345", always as a string. The data object is a gin.H this time, not a struct, so its keys come out sorted alphabetically, account_age_days first and user_id last. A quick map is convenient for a one-off shape, but it gives up the fixed field order and the compile-time checking of a struct.
The last two lines show what happens without an id. /user/ has an empty segment where :id should be, so it does not match the route. Gin's RedirectTrailingSlash option, on by default, notices that the same path without the trailing slash might exist and answers 301 with Location: /api/v1/stats/user. That path does not match /user/:id either, because the parameter needs a segment, so it ends in 404. That is why the handler has no if userID == "" check: the router guarantees id is never empty when the handler runs.
Opening /api/v1/stats/user/12345 on your sandbox URL shows the same object in the browser. Browsers and HTTP clients follow the 301 automatically, so /api/v1/stats/user/ in the address bar ends on the 404 page.
Try it: Change the route to "/user/:id/orders" and restart. Predict what /api/v1/stats/user/12345 returns now, and what /api/v1/stats/user/12345/orders returns. The first is 404, the second is the user's figures: a path parameter covers exactly one segment, and the rest of the pattern must match literally. Change it back.
Summary
We replaced a hand-rolled net/http handler with a Gin API: a health check, versioned route groups, typed models, a handler struct, query parameters with validation, and path parameters. Every endpoint answers with the same success/data/error envelope. The data is random mock data. A database, authentication middleware and request bodies (c.ShouldBindJSON) are deliberately left out.
- A server must listen on every interface on port 9000 (
":9000", an empty host) to be reachable from the sandbox URL. gin.Default()attaches Logger and Recovery; the(3 handlers)in the route table is that chain plus your handler.c.JSON(status, value)writes the status code, setsContent-Type: application/json; charset=utf-8and encodes the value in one call.c.JSONdoes not end the handler; alwaysreturnafter writing an error response.- Struct fields are encoded in declaration order under their
jsontag names;gin.Hmaps are encoded with sorted keys. - Route groups give many routes one prefix, so changing an API version is a one-string change.
- Registering routes with method values makes a missing handler a compile error instead of a runtime
404. c.DefaultQueryreads an optional query parameter with a fallback; validate it against a known set and return400for anything else.:namein a route matches exactly one non-empty segment, andc.Param("name")returns it as a string; use path parameters to identify a resource and query parameters to shape the response.