go框架(4)-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})
})


go框架(4)-gin响应
http://47.123.5.226:8090//archives/gokuang-jia-4--ginxiang-ying
作者
pony
发布于
2024年05月09日
许可协议