一. 响应数据
- 在gin中请求接口响应时,实际可以响应会html,text,plain,json和xml等
- 比如前面gin基础示例中,接口响应时可以使用:
- gin.Context.string(“数据”),表示响应一个字符串
- gin.Context.c.JSON(),设置响应有json
c.String(http.StatusOK, "响应数据")
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
- gin.H是⼀个强⼤的⼯具,有点像map,可以自定义响应的key,value等等
type H map[string]interface{}
- 也可以编写结构体,将指定结构体以json格式响应出去,示例:
type Login struct {
User string `form:"username" json:"user" uri:"user" xml:"user"`
Password string `form:"password" json:"password" uri:"password"xml:"password"`
}
func JsonFunc(c *gin.Context) {
var login Login
if err := c.Bind(&login); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK,login)
}
- 注意点: 响应的结构体不要忘记你打tag
- 另外还有响应xml,yaml,ProtoBuf等
router.GET("/someXML", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"user": "ls", "message": "hey", "status":
http.StatusOK})
})
router.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
router.GET("/someProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
c.ProtoBuf(http.StatusOK, data)
})
二. c.Writer.Header().Set处理响应头
- c.Writer.Header().Set方法是一种设置响应头的方式,它可以接受两个字符串类型的参数,分别表示响应头的名称和值
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/plain")
c.String(200, "Hello, world!")
})
r.Run(":8080")
}