跪拜 Guibai
← Back to the summary

Gin in Practice: Routes, Parameters, and JSON Handling in Go

Gin

Gin is a commonly used HTTP framework in Go. Routes are registered separately by request method, and retrieving parameters and returning JSON require fewer lines than with net/http. It still sits on top of the standard library, so the concepts of "reading requests and writing responses" from the previous post apply here as well.

This post proceeds in a hands-on order:

  1. Upgrade Go to the latest stable version (older versions have compatibility issues with the SSE dependency), or install a separate version by version
  2. Install Gin
  3. Install the hot-reload tool Air, and understand that go install command
  4. Start a minimal service
  5. Pass parameters: path parameters, Query, form, JSON

Middleware and route groups are not covered yet.


1. Go Version: Recommended to Upgrade to the Latest

First check your local version:

go version

Gin depends on github.com/gin-contrib/sse (Server-Sent Events, where the server pushes data to the client as events). There are two layers of issues:

The current latest stable version is Go 1.27.4. The easiest way is to install over the existing version: download the installer for your system from https://go.dev/dl/. On Windows, you can also use:

winget upgrade GoLang.Go

After installing, run go version again, and you should see go1.27.4.

If you don't want to replace the system's go: install a specific version separately

If you already have an old go on your machine and don't want to touch it, you can install another copy of a specific version with two commands:

go install golang.org/dl/go1.27.4@latest
go1.27.4 download
Command What it does
go install golang.org/dl/go1.27.4@latest Installs only a small command named go1.27.4, placed in GOPATH/bin; there is no full toolchain yet
go1.27.4 download Uses the command above to download the Go 1.27.4 toolchain itself

Then in your project, replace go with go1.27.4, for example go1.27.4 mod init, go1.27.4 get ..., go1.27.4 run .. The original go version remains unchanged.


2. Installing Gin

In your module directory (if you don't have a module yet, run go mod init example.com/gin-demo):

go get github.com/gin-gonic/gin@latest

@latest fetches the current latest stable version. At the time of writing, it's v1.12.0, and go.mod requires Go 1.25+, which is why you upgraded earlier.

Add the import in your code and tidy dependencies again:

import "github.com/gin-gonic/gin"
go mod tidy

If module retrieval times out in China, first configure the proxy (covered in the Modules post):

go env -w GOPROXY=https://goproxy.cn,direct

If you used the parallel version from the previous section, replace go with go1.27.4 in those commands as well.


3. Hot Reload: Air

During development, stopping the process and re-running go run after every change is tedious. Air does exactly that: it watches the source files in the project and recompiles and restarts the process on save.

Installation command:

go install github.com/air-verse/air@latest

Let's break it down:

Part Meaning
go install Compiles the program and installs the executable into GOPATH/bin. It does not write into the current project's go.mod, because Air is a local development tool, not a business dependency
github.com/air-verse/air The module path. The earlier repository was at github.com/cosmtrek/air, but it has moved to air-verse; use the new path for installation
@latest Installs the latest version. Air itself requires Go 1.25+, so use the Go you just upgraded

After installing, go to your project directory:

air

It watches .go files with default configuration. To change watch rules, run air init, which generates .air.toml in the current directory.

Remember its boundary: Air is only for writing code on your own machine. For production, you still run a normal go build to produce a binary; you won't rely on Air for hot restarts in production.

On Windows, if you get a "air not found" error, add the bin directory under go env GOPATH to PATH (commonly C:\Users\your username\go\bin), and open a new terminal before running it again. With the parallel install, use go1.27.4 install github.com/air-verse/air@latest, and the installed command also goes in that bin directory.


4. Minimal Service

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	router.GET("/", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, "你好")
	})

	if err := router.Run(); err != nil {
		panic(err)
	}
}
API Purpose
gin.Default() Creates an engine with built-in access logging and panic recovery
router.GET(path, handler) Only accepts GET. For POST, write router.POST
ctx.String(statusCode, format, args...) Writes a text response; format is the same as fmt.Sprintf
router.Run() Listens on :8080. Writing router.Run(":8080") is the same

*gin.Context handles both reading the current request and writing the current response, corresponding to r and w in the standard library.

After starting with go run . or air, open http://localhost:8080 in the browser to see 「你好」. If the port is occupied, Run returns an error; here we panic to print the reason to the terminal.


5. Passing Parameters

Data in an interface usually comes from four places:

Method What it looks like How to retrieve
Path parameter /user/12 ctx.Param("id")
Query /user?id=1&name=小满 ctx.DefaultQuery / ctx.Query
Form POST, body is id=1&name=小满 ctx.DefaultPostForm
JSON POST, body is {"name":"小满","age":18} ctx.ShouldBindJSON

Below, each is shown briefly, and finally combined into a runnable main.go.

Path Parameters

Use :name in the path to occupy one segment:

router.GET("/user/:id", func(ctx *gin.Context) {
	id := ctx.Param("id") // /user/12 → "12"
	ctx.String(http.StatusOK, "id=%s", id)
})

Param always returns a string. If the request is /user/12, id is "12", not automatically converted to a number.

Query

The key-value pairs after the question mark are used for optional conditions like "filter" and "search":

router.GET("/user", func(ctx *gin.Context) {
	id := ctx.DefaultQuery("id", "none")
	name := ctx.DefaultQuery("name", "none")
	ctx.String(http.StatusOK, "id=%s name=%s", id, name)
})

The second argument to DefaultQuery is the default value when the key is absent. With /user and no params, both are none; with /user?id=1&name=小满, the actual values are retrieved.

As long as a key is present, even if its value is empty (?name=), the default is not used. To treat an empty string as "not present", use ctx.Query("name"), which returns "" when missing.

/user/:id and /user can be registered simultaneously: one requires an extra path segment, the other is just /user itself; Gin can tell them apart.

Form

When the POST body is a form (application/x-www-form-urlencoded or multipart/form-data), use DefaultPostForm. The second argument is also the default value when the field is absent:

router.POST("/user/formdata", func(ctx *gin.Context) {
	id := ctx.DefaultPostForm("id", "none")
	name := ctx.DefaultPostForm("name", "none")
	ctx.String(http.StatusOK, "id=%s name=%s", id, name)
})

It reads from the Body, not from the URL's ?id=1. Using the Query functions to read form data will always return the default value.

JSON

Define a struct; fields must be capitalized to be populated. The `json` tag determines the JSON name, and the `binding` tag determines whether to validate:

type User struct {
	Name string `json:"name" binding:"required"`
	Age  int    `json:"age"`
}

The tag is binding; missing one letter means no validation, and the request can still come through.

router.POST("/user/create", func(ctx *gin.Context) {
	var user User
	if err := ctx.ShouldBindJSON(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusCreated, gin.H{
		"code":    1,
		"data":    user,
		"success": true,
	})
})

ShouldBindJSON does two things: it populates the struct from the body according to the json tags, then checks according to the binding tags. Name is marked required; missing name or an empty string returns an error. Age is not marked; if not passed, it becomes 0.

On failure, you must return. Otherwise the function continues, and the same response writes 400 then 201.

gin.H is an alias for map[string]any, used to quickly compose a JSON object. ctx.JSON sets Content-Type: application/json and serializes. Here, success uses 201 Created, and invalid parameters use 400 Bad Request.

The request requires:

Putting It Together

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type User struct {
	Name string `json:"name" binding:"required"`
	Age  int    `json:"age"`
}

func main() {
	router := gin.Default()

	router.GET("/", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, "你好")
	})

	// Path parameter: /user/12
	router.GET("/user/:id", func(ctx *gin.Context) {
		id := ctx.Param("id")
		ctx.String(http.StatusOK, "id=%s", id)
	})

	// Query: /user?id=1&name=小满
	router.GET("/user", func(ctx *gin.Context) {
		id := ctx.DefaultQuery("id", "none")
		name := ctx.DefaultQuery("name", "none")
		ctx.String(http.StatusOK, "id=%s name=%s", id, name)
	})

	// Form body: id=1&name=小满
	router.POST("/user/formdata", func(ctx *gin.Context) {
		id := ctx.DefaultPostForm("id", "none")
		name := ctx.DefaultPostForm("name", "none")
		ctx.String(http.StatusOK, "id=%s name=%s", id, name)
	})

	// JSON body: {"name":"小满","age":18}
	router.POST("/user/create", func(ctx *gin.Context) {
		var user User
		if err := ctx.ShouldBindJSON(&user); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		ctx.JSON(http.StatusCreated, gin.H{
			"code":    1,
			"data":    user,
			"success": true,
		})
	})

	if err := router.Run(); err != nil {
		panic(err)
	}
}

Check with curl (service already on 8080):

curl http://localhost:8080/
curl http://localhost:8080/user/12
curl "http://localhost:8080/user?id=1&name=小满"
curl -X POST http://localhost:8080/user/formdata -d "id=1&name=小满"
curl -X POST http://localhost:8080/user/create \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"小满\",\"age\":18}"
Request Result
GET / 你好
GET /user/12 id=12
GET /user?id=1&name=小满 id=1 name=小满
GET /user id=none name=none
POST /user/formdata, body id=1&name=小满 id=1 name=小满
POST /user/create, body {"name":"小满","age":18} 201, data contains the user
POST /user/create, body {} 400, indicating name is required

Summary

Topic What to remember
Go version Upgrade to the latest stable (currently 1.27.4). Old Go and the new gin-contrib/sse don't match; if you don't want to overwrite, run go install golang.org/dl/go1.27.4@latest then download
Installing Gin go get github.com/gin-gonic/gin@latest, then go mod tidy
Air go install github.com/air-verse/air@latest, run air in the project directory. It watches files and restarts the process, use only for local development
Startup gin.Default() registers routes, router.Run() listens on :8080
Path parameter /user/:id, use ctx.Param("id"), result is a string
Query ctx.DefaultQuery("id", "none"), second argument is the default when the key is absent
Form ctx.DefaultPostForm, reads POST body, not URL
JSON Struct with json / binding tags, ShouldBindJSON binds; on failure return, then write response with ctx.JSON