0%

gin-响应体的返回

gin-响应体的返回:

  • 响应字符串:
func _string(context *gin.Context) {
context.String(http.StatusOK, "我是你爸爸")
}

func main() {
router.GET("/string", _string)
}
  • 响应Json:
func _json(context *gin.Context) {

// 方式:一
// 创建结构体
type UserInfo struct {
UserName string `json:"user_name"` // 渲染json 为后面的小写 user_name
Age int `json:"age"`
PassWord string `json:"-"` // 在json 中 "-" 表示不渲染该项
}
// 在结构体中添加数据 => Json
//user := UserInfo{"李小屁", 25, "123456"}
//context.JSON(200, user)

// 方式:二
// json 响应map
//userMap := map[string]string{
// "user_name": "李小头",
// "age": "23",
//}
//context.JSON(200, userMap)

// 方式:三
//直接响应 Json 数据
context.JSON(200, gin.H{"user_name": "李中头", "age": 28})

}

func main() {
router.GET("/json", _json)
}
  • 响应 xml:
// 响应 xml
func _xml(context *gin.Context) {
context.XML(http.StatusOK, gin.H{"user": "hanru", "message": "hey", "status": http.StatusOK, "data": gin.H{"user": "李大头"}})
}

func main() {
router.GET("/xml", _xml)
}
  • 响应 yaml:
// 响应 xml
func _yaml(context *gin.Context) {
context.YAML(http.StatusOK, gin.H{"user": "hanru", "message": "hey", "status": http.StatusOK, "data": gin.H{"user": "李大头"}})
}

func main() {
router.GET("/yaml", _yaml) // 这里需要注意的是,返回yaml 文件 某些浏览器会自动下载
}
  • 响应 html:
func _html(context *gin.Context) {
println(_time())
context.HTML(200, "index.html", gin.H{})
}

// 其中 加载静态文件 和 html模板文件
func main() {
router.LoadHTMLGlob("templates/*")
router.Static("/static", "./static")
}

  • 响应文件:
router.StaticFile("/static", "static/cc.png")   //没有对应的函数,直接返回

响应文件

重定向:

// 响应跳转 302
func _redirect(context *gin.Context) {
context.Redirect(302, "https://www.baidu.com")
}
func main() {
router.GET("/baidu", _redirect) // 301: 永久重定向, 302:临时重定向
}