Gin封装的最好的地方就是context和对response的处理
一、context
Context的最佳运用场景就是对Http的处理
Context是Gin最重要的部分。它允许我们在中间件之间 传递变量,管理流程,验证请求的JSON 并 呈现JSON响应。
1、Metadata Management
type Context struct {
...
Keys map[string]interface{}
...
}
gin获取或设置Context的Key-Value(键值对)
INPUT DATA
2、Param(路由变量)
例:restful风格api如/user/john, 这个路由在gin里面是/user/:name, 要获取john就需要使用Param函数:name := c.Param("name")
3、Query
/welcome?firstname=Jane&lastname=Doe这样一个路由, first, last即是Querystring parameters, 要获取他们就需要使用Query相关函数.
c.Query("first") // Jane c.Query("last") // Doe
4、PostForm
对于POST, PUT等这些能够传递参数Body的请求, 要获取其参数, 需要使用PostForm
5、Bind
有json, xml, protobuf, form, query, yaml的bind。极大的减少我们自己去解析各种各样的数据格式。
context.BindJSON() 支持MIME为application/json的解析
context.BindXML() 支持MIME为application/xml的解析
context.BindYAML() 支持MIME为application/x-yaml的解析
context.BindQuery() 只支持QueryString的解析, 和Query()函数一样
context.BindUri() 只支持路由变量的解析
RESPONSE RENDERING
6、Header
对于客户端发的请求的Header可以通过context.Request.Header.Get("Content-Type")获取,
context.Writer.Header().Set(key, value)
7、render
- func (c *Context) JSON(code int, obj interface{})
- func (c *Context) Protobuf(code int, obj interface{})
- func (c *Context) YAML(code int, obj interface{})
...
我们常用的是一个方法是: gin.H{"error": 111}.
这个结构相当实用, 各种render都支持。其实这个结构很简单就是type H map[string]interface{}