3

In general, there are two types of web development based on the Gin framework:

  • The first is that the backend uses the go language template engine to complete the entire web full-stack development and returns the complete html file to the browser.
  • The second is to separate the front and back ends and use JSON to interact

Because the first method consumes too many network resources, has poor performance and high coupling, it has been basically replaced by the second mode. This blog only introduces how to return JSON data to the front end or mobile terminal in the Gin framework (commonly known as JSON rendering).


To generate JSON data, you can use map or structure. Let's first introduce the map:

Map-based JSON data generation

For example, the code is as follows:

 package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    r := gin.Default()
    r.GET("/json", func(c *gin.Context) {
        //这里构造服务器要返回前端的数据,一共有两种方法,第一种是:使用map将数据序列化
        //,这个map的key是一个string, value是一个空的接口(这样即可以实现接收任意类型的数据)
        data := map[string]interface{}{
            "name":    "liber",
            "message": "hey liber~",
            "age":     16,
        }
        //这里要返回json格式的数据,所以用c.JSON,这样,数据就返回给请求方了
        c.JSON(http.StatusOK, data)
    })
    r.Run(":9090")
}

The test results are as follows:

Since it is very common to use map to serialize json data, the author of the Gin framework encapsulates this way of writing:

 //H is a shortcut for map[string]interface{}
type H map[string]interface{}

So, we can use gin.H{} directly instead:

 package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    r := gin.Default()
    r.GET("/json", func(c *gin.Context) {
        //这里构造服务器要返回前端的数据,一共有两种方法,第一种是:使用map将数据序列化
        //,这个map的key是一个string, value是一个空的接口(这样即可以实现接收任意类型的数据)
        //data := map[string]interface{}{
        //    "name":    "liber",
        //    "message": "hey liber~",
        //    "age":     16,
        //}
        data := gin.H{
            "name":    "libro",
            "message": "hey libro~",
            "age":     17,
        }
        //这里要返回json格式的数据,所以用c.JSON,这样,数据就返回给请求方了
        c.JSON(http.StatusOK, data)
    })
    r.Run(":9090")
}

The test results are as follows:

Structure-based JSON data generation

In fact, it is just another way of writing:

 package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    r := gin.Default()
    r.GET("/json", func(c *gin.Context) {
        //这里构造服务器要返回前端的数据,一共有两种方法,第一种是:使用map将数据序列化
        //,这个map的key是一个string, value是一个空的接口(这样即可以实现接收任意类型的数据)
        //data := map[string]interface{}{
        //    "name":    "liber",
        //    "message": "hey liber~",
        //    "age":     16,
        //}
        data := gin.H{
            "name":    "libro",
            "message": "hey libro~",
            "age":     17,
        }
        //这里要返回json格式的数据,所以用c.JSON,这样,数据就返回给请求方了
        c.JSON(http.StatusOK, data)
    })

    //这里介绍生成JSON数据的第二种方法:利用结构体
    //首先构造一个结构体
    type msg struct {
        Name    string
        Message string
        Age     int
    }
    //然后构建一个结构体的实例
    r.GET("/another_json", func(c *gin.Context) {
        data := msg{
            Name:    "libro",
            Message: "hey libro~",
            Age:     17,
        }
        c.JSON(http.StatusOK, data)
    })
    r.Run(":9090")
}

The test results are shown in the figure:

However, it should be noted that if a structure is used, the first letter of the field must be capitalized, otherwise the serialization of JSON cannot be completed, because the built-in reflection mechanism of Go is used in the JSON serialization process, and lowercase means that it cannot be exported. Of course, there is also a solution to this, that is to tag:

 //这里假设 前端就需要小写的name
    type msg struct {
        Name    string `json: "name"`
        Message string
        Age     int
    }

In fact, I think that since there are pits, it is a simple and wise choice to directly stipulate that the first method is used to avoid them.


Reference: bilibili

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com