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})
})

 

posted @ 2023-03-16 15:59  佛祖让我来巡山  阅读(30)  评论(0编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网