Gin 響應方式

響應

1. 字符串方式

r.GET("/user/save", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, "this is a %s", "ms string response")
})

2. JSON方式

r.GET("/user/save", func (ctx *gin.Context) {
    ctx.JSON(http.StatusOK, gin.H{
        "success": true,
    })
})

3. XML方式

type XmlUser struct {
    Id   int64  `xml:"id"`
    Name string `xml:"name"`
}
r.GET("/user/save", func (ctx *gin.Context) {
    u := XmlUser{
        Id:   11,
        Name: "zhangsan",
    }
    ctx.XML(http.StatusOK, u)
})

4. 文件格式

r.GET("/user/save", func (ctx *gin.Context) {
    //ctx.File("./1.png")
    ctx.FileAttachment("./1.png", "2.png")
})

5. 設置http響應頭

r.GET("/user/save", func(ctx *gin.Context) {
    ctx.Header("test", "headertest")
})

6. 重定向

r.GET("/user/save", func(ctx *gin.Context) {
    ctx.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
})

7. YAML方式

r.GET("/user/save", func(ctx *gin.Context) {
    ctx.YAML(200, gin.H{"name": "ms", "age": 19})
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章