2.2 Gin Handler Functions
In the Gin framework, a handler function is a function used to process incoming requests, responsible for executing business logic and returning responses to the client. Handler functions are typically defined as a function that takes <span>*gin.Context</span> as a parameter.<span>*gin.Context</span> provides methods to access request information (such as URL, HTTP headers, request body, etc.) and to send responses back to the client. An example is shown below:
package main
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func MockQueryUserByIdFromDB(id int) (int, error) {
if id == 123 {
return id, nil
}
return 0, errors.New("query user error")
}
// Handler function
func getUserById(ctx *gin.Context) {
requestId, _ := strconv.Atoi(ctx.Param("id"))
queryId, err := MockQueryUserByIdFromDB(requestId)
if err != nil {
ctx.JSON(http.StatusNotFound, gin.H{
"error": "user not found",
})
return
}
ctx.JSON(http.StatusOK, queryId)
}
func main() {
r := gin.Default()
r.GET("/user/:id", getUserById)
// Default listening on 0.0.0.0:8080
r.Run()
}
In the above code, getUserById() is a handler function that accesses the id parameter from the URL using *gin.Context and retrieves user information based on the id. If the user exists, it returns the information in JSON format; otherwise, it returns an error message indicating that the user does not exist.