{{ .title }}
Using posts/index.tmpl
{{ end }} user.tmpl 1 2 3 4 5 6 7 {{ define "users/index.tmpl" }}{{ .title }}
Using users/index.tmpl
{{ end }} 对应的HTML模板文件目录结构如下 代码部分 router.LoadHTMLGlob用于指明HTML模板文件的路径 router.GET同上,定义访问路由和返回结果,不同于第一个Demo的是,这里有赋值填充的过程,比如 1 2 3 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) 将index.tmpl中定义的 .title替换为"Posts" 执行结果如下 2、PureJSON 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 func main() { r := gin.Default() // 提供 unicode 实体 r.GET("/json", func(c *gin.Context) { c.JSON(200, gin.H{ "html": "Hello, 世界!", }) }) // 提供字面字符 r.GET("/purejson", func(c *gin.Context) { c.PureJSON(200, gin.H{ "html": "Hello, 世界!", }) }) // 监听并在 0.0.0.0:8080 上启动服务 r.Run(":8080") } 这里两个GET方法唯一不同的就是要渲染的内容一个使用JSON()方法一个使用PureJSON()方法。 启动程序后,我们看下访问结果有什么不同 可以看出JSON()渲染的会有中文以及标签转为unicode编码,但是使用PureJSON()渲染就是原样输出(我的浏览器装了插件,会自动解码,所以不点击右边的”RAW“两个接口返回的结果是一样的)。 这个问题,本周我们服务端在和客户端对接的时候还遇到了,因为框架返回的JSON串就是经过编码的,但是单独请求放到浏览器是没有问题的,客户端收到的却是经过编码的,最后排查发现是浏览器插件解码了。 3、渲染多种数据交换格式的数据 gin支持渲染XML、JSON、YAML和ProtoBuf等多种数据格式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/testdata/protoexample" "net/http" ) func main() { r := gin.Default() // gin.H 是 map[string]interface{} 的一种快捷方式 r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // 你也可以使用一个结构体 var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // 注意 msg.Name 在 JSON 中变成了 "user" // 将输出:{"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // protobuf 的具体定义写在 testdata/protoexample 文件中。 data := &protoexample.Test{ Label: &label, Reps: reps, } // 请注意,数据在响应中变为二进制数据 // 将输出被 protoexample.Test protobuf 序列化了的数据 c.ProtoBuf(http.StatusOK, data) }) // 监听并在 0.0.0.0:8080 上启动服务 r.Run(":8080") } 今天先到这,后面再看看gin的源码。 如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!如果您想持续关注我的文章,请扫描二维码,关注JackieZheng的微信公众号,我会将我的文章推送给您,并和您一起分享我日常阅读过的优质文章。 https://www.cnblogs.com/bigdataZJ/p/gin-helloworld.html