gin 响应
状态码 200 表示正常响应 http.StatusOK 响应 返回字符串 router.GET("/txt", func(c *gin.Context) { c.String(ht
gin 响应
发布时间:2023-10-07 (2023-10-07)

状态码

200 表示正常响应 http.StatusOK

响应

返回字符串

router.GET("/txt", func(c *gin.Context) {
  c.String(http.StatusOK, "返回txt")
})

返回json

router.GET("/json", func(c *gin.Context) {
  c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
// 结构体转json
router.GET("/moreJSON", func(c *gin.Context) {
  // You also can use a struct
  type Msg struct {
    Name    string `json:"user"`
    Message string
    Number  int
  }
  msg := Msg{"fengfeng", "hey", 21}
  // 注意 msg.Name 变成了 "user" 字段
  // 以下方式都会输出 :   {"user": "hanru", "Message": "hey", "Number": 123}
  c.JSON(http.StatusOK, msg)
})

返回xml

router.GET("/xml", func(c *gin.Context) {
  c.XML(http.StatusOK, gin.H{"user": "hanru", "message": "hey", "status": http.StatusOK})
})

返回yaml

router.GET("/yaml", func(c *gin.Context) {
  c.YAML(http.StatusOK, gin.H{"user": "hanru", "message": "hey", "status": http.StatusOK})
})

返回html

先要使用 LoadHTMLGlob()或者LoadHTMLFiles()方法来加载模板文件

//加载模板
router.LoadHTMLGlob("gin框架/templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
//定义路由
router.GET("/tem", func(c *gin.Context) {
  //根据完整文件名渲染模板,并传递参数
  c.HTML(http.StatusOK, "index.html", gin.H{
    "title": "Main website",
  })
})

在模板中使用这个title,需要使用{{ .title }}

不同文件夹下模板名字可以相同,此时需要 LoadHTMLGlob() 加载两层模板路径。

router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
    c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
        "title": "Posts",
    })
    c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
        "title": "Users",
    })

})

文件响应

// 在golang总,没有相对文件的路径,它只有相对项目的路径
// 网页请求这个静态目录的前缀, 第二个参数是一个目录,注意,前缀不要重复
router.StaticFS("/static", http.Dir("static/static"))
// 配置单个文件, 网页请求的路由,文件的路径
router.StaticFile("/titian.png", "static/titian.png")

重定向

router.GET("/redirect", func(c *gin.Context) {
    //支持内部和外部的重定向
    c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
})

301 Moved Permanently

被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个 URI 之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。

302 Found

请求的资源现在临时从不同的 URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。