gin返回string
func String(c *gin.Context) {
c.String(http.StatusOK, "返回字符串示例")
}
gin返回json
func Json(c *gin.Context) {
data := map[string]string{
"name": "bxy",
}
c.JSON(http.StatusOK, data)
}
gin返回html
- 这里使用到了go的模板语法,不在此次详细讲解,只需要了解gin如何返回html模板的步骤即可。
- gin.H实际上就是一个map数据结构
<html>
<h1>
{{ .title }}
</h1>
</html>
func OnInit(r *gin.Engine) {
r.LoadHTMLGlob("gin/templates/*.tmpl")
}
func Html(c *gin.Context) {
c.HTML(http.StatusOK, "title.tmpl", gin.H{
"title": "hello gin",
})
}
gin返回xml
func Xml(c *gin.Context) {
c.XML(http.StatusOK, gin.H{
"name": "bxy",
"age": 100,
})
}
gin返回yaml
- 使用yaml格式返回数据时,前端会将数据按yaml格式的文件进行下载。
func Yaml(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{
"name": "bxy",
"age": 10,
})
}