本文主要记录一下自己学习gin框架过程中亲自写的一些练习与笔记,温故而知新。
全部是参考这篇博客:https://www.liwenzhou.com/posts/Go/Gin_framework/#autoid-0-8-3
另外,所有的代码均使用testing实现,需要将go文件的名称命名为xxx_test.go。
使用gin.H发送嵌套字典的响应
有时候需要发送字典嵌套的响应,像这样:
实际上可以这样写返回的响应:
// home路由 func homeHandler(c *gin.Context){ // 获取参数 username := c.MustGet("username").(string) // 返回响应 c.JSON(http.StatusOK, gin.H{ "code": 2000, "msg": "success", "data": gin.H{"username":username}, }) }
基本请求与响应的处理以及启动服务
package t_ginProjets import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/testdata/protoexample" "net/http" "testing" ) // 视图函数 GET请求 func hello(c *gin.Context) { // c.JSON,返回json格式的数据 // TODO 返回JSON的方式一:自己拼接JSON c.JSON(http.StatusOK, gin.H{ "name": "whw", "message": "hello world!", }) } // POST请求 func postMethod(c *gin.Context) { // TODO 返回JSON的方式二:使用结构体 var msg struct { Name string `json:"post_name"` // 注意最终json的变量名是后面的! Age int `json:"post_age"` Message string `json:"post_message"` } // 创建一个结构体对象 msg.Name = "whw" msg.Age = 18 msg.Message = "666666" // TODO 直接将结构体对象传入参数中即可 c.JSON(200, msg) } // PUT请求 func putMethod(c *gin.Context) { c.JSON(200, gin.H{ "name": "putMethod", "msg": "hello put", }) } // DELETE请求 func deleteMethod(c *gin.Context) { c.JSON(200, gin.H{ "name": "deleteMethod", "msg": "hello delete", }) } // TODO 简单的请求与响应处理 + json渲染 + protobuf渲染 + 启动服务 func TestGinReq(t *testing.T) { // 路由引擎 r := gin.Default() // GET r.GET("/hello", hello) // POST r.POST("/post", postMethod) // PUT 传入匿名函数的方式 r.PUT("/put", func(c *gin.Context) { c.JSON(200, gin.H{ "name": "myPutMethod", "msg": "HELLO PUT", }) }) // DELETE r.DELETE("/delete", deleteMethod) // protobuf渲染 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) }) // 启动HTTP服务 什么都不写默认是 0.0.0.0:8080 r.Run("127.0.0.1:9000") }