Go by Example: Building APIs with Gin
Go 1.23
Build high-performance web APIs with the Gin framework. This example introduces Gin's routing capabilities, JSON response handling, and request binding, showcasing why it's a popular choice for modern Go web development.
Code
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.POST("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
c.JSON(200, gin.H{
"id": id,
"page": page,
"name": name,
"message": message,
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}Explanation
Gin is a high-performance HTTP web framework written in Go (Golang). It features a martini-like API but with performance up to 40 times faster than Martini, thanks to its custom httprouter. Gin is designed for building scalable, robust RESTful APIs with minimal boilerplate.
Why Gin is a Top Choice:
- Middleware Ecosystem: Gin has a vast library of middleware for common tasks like logging, CORS, authentication, and GZIP compression, allowing you to compose your application logic efficiently.
- JSON Validation: It offers built-in support for request data binding and validation. You can bind JSON, XML, or form data directly to Go structs using tags, ensuring data integrity at the entry point.
- Error Management: Gin provides a convenient way to collect all errors that occurred during a request and render them in a standardized JSON response.
Code Breakdown
9
gin.Default() creates a router with the Logger and Recovery middleware already attached. Use gin.New() if you want a completely blank slate.
11
r.GET registers a handler for the GET HTTP method. The handler function takes a *gin.Context, which is the heart of Gin, containing the request, response writer, and parameters.
12
c.JSON serializes the given struct or map into JSON and writes it to the response body. It also sets the Content-Type header to "application/json".
18
c.Query("id") extracts the "id" parameter from the URL query string (e.g., ?id=123). If the parameter is missing, it returns an empty string.
19
c.DefaultQuery("page", "0") is similar to Query, but it returns the specified default value ("0") if the "page" parameter is not present in the URL.
20
c.PostForm("name") retrieves data from a POST request body (typically x-www-form-urlencoded). For JSON bodies, you would use c.BindJSON(&struct).
31
r.Run() starts the web server. By default, it listens on port 8080 on all interfaces. You can pass a string like ":3000" to change the port.

