1.使用map[string]interfave{} 或者gin内置的gin.H{}
2.使用struct 也可以进行使用tag来对struct字段做定制化操作
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/json", func(c *gin.Context) {
//方法1:使用map序列化
data := map[string]interface{}{
"name": "小王子",
"message": "饿了",
"age": 10,
}
c.JSON(http.StatusOK, data) //将json数据返回给请求方
})
//方法2:结构体
type msg struct {
Name string `json:"我的"`
Message string
Age int
}
r.GET("/another_json", func(c *gin.Context) {
data := msg{
Name: "张三",
Message: "Hello world",
Age: 10,
}
c.JSON(http.StatusOK, data)
})
r.Run(":9090")
}