Golang框架Gin入门实战–(2)Gin路由中响应数据 c.String() c.JSON() c.JSONP() c.XML() c.HTML()
代码语言:javascript复制package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Article struct {
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
func main() {
r := gin.Default()
// 配置模板的文件
r.LoadHTMLGlob("templates/*")
r.GET("/", func(c *gin.Context) {
c.String(200, "值:%v", "首页")
})
r.GET("/json1", func(c *gin.Context) {
c.JSON(200, map[string]interface{}{
"success": true,
"msg": "你好gin",
})
})
r.GET("/json2", func(c *gin.Context) {
c.JSON(200, gin.H{
"success": true,
"msg": "你好gin--2",
})
})
r.GET("/json3", func(c *gin.Context) {
a := &Article{
Title: "我是一个标题",
Desc: "描述",
Content: "测试内容",
}
c.JSON(200, a)
})
// 响应jsonp请求
//主要处理跨域问题
//http://localhost:8080/jsonp?callback=xxxx
//xxxx({"title":"我是一个标题-jsonp","desc":"描述","content":"测试内容"});
r.GET("/jsonp", func(c *gin.Context) {
a := &Article{
Title: "我是一个标题-jsonp",
Desc: "描述",
Content: "测试内容",
}
c.JSONP(200, a)
})
r.GET("/xml", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{
"succes": true,
"msg": "你好gin 我是一个xml",
})
})
r.GET("/news", func(c *gin.Context) {
//r.LoadHTMLGlob("templates/*")
c.HTML(200, "news.html", gin.H{
"title": "我是后台的数据",
})
})
r.GET("/goods", func(c *gin.Context) {
//r.LoadHTMLGlob("templates/*")
c.HTML(200, "goods.html", gin.H{
"title": "我是商品页面",
"price": 20,
})
})
r.Run()
}
HTML渲染需要注意在路由引擎上添加
代码语言:javascript复制 // 配置模板的文件
r.LoadHTMLGlob("templates/*")
在demo目录下创建templates文件夹,并生成两个html5文件
(1)news.html
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>{{.title}}</h2>
</body>
</html>
(2)goods.html
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>{{.title}}</h2>
<br>
{{.price}}
<br>
<h5>html的数据</h5>
</body>
</html>