您的位置 首页 golang

golang gin Context结构解读 学习系列(二)

今天主要学习一下 golang gin框架,主要学习一下Context结构体。GIN 是Go语言的轻量HTTP框架

▎介绍

Context 是gin框架贯穿整个请求的上下文,从请求开始到请求完成无论是在middleware/handle中,我们可以通过context对象获取到请求的信息,响应的信息,可以在context中设置一些自定义参数,在整个请求的过程都可以获取。

▎Context 公开属性

context的public属性

我们开始学习一下每个属性的含义:

  1. Request 属性是Http请求的信息都可以通过此属性获取,如:请求的 Header 信息,Cookies,Agent等等

  2. Writer 属性是响应对象,在这里可以设置响应的各种信息,如:Content-Type,HttpCode 等等

  3. Params 属性是路由中动态参数的param.如:注意一个路由app.GET(“/:user”,func(c *gin.Context))此时我们就可以通过c.Params[“user”]获取到此信息

  4. Keys 属性是用来存在自定义参数,会在此次请求中一直存在知道请求完成

  5. Errors 属性和Keys类似可以用来存在整个请求过程中的错误信息

  6. Accepted 属性主要是用来动态的设置响应的格式,与context.Negotiate()方法一起使用时起作用

Context 公开的方法

A.工具方法

  • func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) //此方法主要是用于在开发的时候进行测试,传入一个responseWriter 方法会返回一个context和engine用户测试context是否是需要的数据,下面是一个简单的测试用例

  • func (c *Context) ClientIP() string //获取客户端IP

  • func (c *Context) ContentType () string //获取请求的ContentType

  • func (c *Context) Cookie (name string) (string, error) //获取Cookie的值

  • func (c *Context) Copy() *Context //克隆一个context,官方说明到需要在请求中是用异步,请使用此方法

  • func (c *Context) Data(code int, contentType string, data [] byte ) //返回数据,自定响应的ContentType

  • func (c *Context) Deadline() (deadline time.Time, ok bool) //暂无逻辑

  • func (c *Context) Done() <-chan struct{} //暂无逻辑

  • func (c *Context) Err() error //暂无逻辑

  • func (c *Context) Error(err error) *Error //在当前请求的错误队列中增加错误记录

  • func (c *Context) Handler() HandlerFunc //获取下一个要执行的handlerfunc

  • func (c *Context) HandlerName() string //获取下一个要执行的handler名称

  • func (c *Context) Header(key, value string) //设置Http响应头

  • func (c *Context) IsAborted() bool //此次请求是否已经终止

  • func (c *Context) IsWebsocket() bool //此次请求是否为websocket

  • func (c *Context) Next() //执行下一个handle方法

上下文中自定参数

  • func (c *Context) Set(key string, value interface{}) //设置自定义数据

  • func (c *Context) Get(key string) (value interface{}, exists bool) //获取自定义参数值interface{}

  • func (c *Context) GetBool(key string) (b bool) //获取自定义参数值转bool

  • func (c *Context) GetDuration(key string) (d time.Duration)//获取自定义参数值转time.Duration

  • func (c *Context) GetFloat64(key string) (f64 float64) //获取自定义参数值转float64

  • func (c *Context) GetInt(key string) (i int) //获取自定义参数值转int

  • func (c *Context) GetInt64(key string) (i64 int64) //获取自定义参数值转int64

  • func (c *Context) GetString(key string) (s string) //获取自定义参数值转string

  • func (c *Context) GetStringMap(key string) (sm map[string]interface{}) //获取自定义参数值转map[string]interface{}

  • func (c *Context) GetStringMapString(key string) (sms map[string]string) //获取自定义参数值转map[string]string

  • func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) //获取自定义参数值转map[string][]string

  • func (c *Context) GetStringSlice(key string) (ss []string)//获取自定义参数值转[]string

  • func (c *Context) GetTime(key string) (t time.Time)//获取自定义参数值转time.Time

  • func (c *Context) MustGet(key string) interface{} //获取自定义参数如果不存在则抛出错误

  • func (c *Context) Value(key interface{}) interface{} //此方法没有用处建议不用尝试了

请求参数的获取与解析方法

  • func (c *Context) Bind(obj interface{}) error //请求数据映射到struce或者map中,内部使用工厂模式进行判断,支持json,form,xml等,当解析失败时返回error,并执行abortwitherror

  • func (c *Context) BindJSON(obj interface{}) error //类似于Bind,注意支持json映射

  • func (c *Context) BindQuery(obj interface{}) error //类似于Bind,注意支持get参数映射

  • func (c *Context) BindWith(obj interface{}, b binding.Binding) error //类似于Bind,自定义映射

  • func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) //自定义请求数据解析规则失败自动终止请求

  • func (c *Context) ShouldBind(obj interface{}) error //动态解析请求数据,无法解析只返回error不终止请求

  • func (c *Context) ShouldBindJSON(obj interface{}) error //动态解析POST请求json数据,无法解析只返回error不终止请求

  • func (c *Context) ShouldBindQuery(obj interface{}) error //动态解析GET请求数据,无法解析只返回error不终止请求

  • func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error //动态解析请求数据,无法解析只返回error不终止请求,自定义解析器

  • func (c *Context) Param(key string) string //获取pathinfo中的值

  • func (c *Context) PostForm(key string) string //获取PostForm的值

  • func (c *Context) PostFormArray(key string) []string //获取POSTFORM的值,并转ARRAY

  • func (c *Context) DefaultPostForm(key, defaultValue string) string// 获取POST Form参数支持设置默认值

  • func (c *Context) DefaultQuery(key, defaultValue string) string //获取get请求的参数值,支持默认值设置

  • func (c *Context) Query(key string) string //获取GET参数值

  • func (c *Context) QueryArray(key string) []string //获取get参数值并转数组

  • func (c *Context) MultipartForm() (*multipart.Form, error) //获取上传文件

  • func (c *Context) GetHeader(key string) string //获取HttpHeader中指定Key的值

  • func (c *Context) GetPostForm(key string) (string, bool) //获取POST参数并返回是否存在

  • func (c *Context) GetPostFormArray(key string) ([]string, bool) //获取POST参数转数组并返回是否存在

  • func (c *Context) GetQuery(key string) (string, bool) //获取get参数并返回是否存在

  • func (c *Context) GetQueryArray(key string) ([]string, bool) //获取个体参数转数组并返回是否存在

  • func (c *Context) GetRawData() ([]byte, error) //获取原始请求数据

  • func (c *Context) FormFile(name string) (*multipart.FileHeader, error) //获取上传文件的指定名称的文件内容

  • func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error //保存上传的文件到指定目录

响应与渲染

  • func (c *Context) XML(code int, obj interface{}) //响应XML数据

  • func (c *Context) YAML (code int, obj interface{})//响应YAML数据

  • func (c *Context) HTML(code int, name string, obj interface{})//http响应html文件

  • func (c *Context) IndentedJSON(code int, obj interface{}) //http响应缩进的Json

  • func (c *Context) JSON(code int, obj interface{}) //http响应json数据

  • func (c *Context) JSONP(code int, obj interface{}) //http响应jsonp

  • func (c *Context) SecureJSON(code int, obj interface{}) //响应安全的json数据

  • func (c *Context) Redirect(code int, location string) //重定向

  • func (c *Context) Render (code int, r render.Render) //自定义响应渲染引擎

  • func (c *Context) File(filepath string) //指定文件写入response中

  • func (c *Context) SSEvent(name string, message interface{}) //服务器想客户端主动推送信息,注意:目前不是所有的浏览器都支持

  • func (c *Context) Status(code int) //设置响应的HttpStatus

  • func (c *Context) Stream(step func(w io.Writer) bool) //自定义响应方法

  • func (c *Context) String(code int, format string, values …interface{}) //响应text/plain数据

  • func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) //设置响应cookie

  • func (c *Context) SetAccepted(formats …string) //设置响应数据规则,与下面两个方法配合使用

  • func (c *Context) Negotiate(code int, config Negotiate) //根据响应规则动态响应数据

  • func (c *Context) NegotiateFormat(offered …string) string //获取响应数据规则

终止请求的方法

  • func (c *Context) Abort() //多数被用于中间件中,如有个 鉴权 校验当鉴权不通过时,我们可以通过abort方法来忽略后续的处理

  • func (c *Context) AbortWithError(code int, err error) *Error //等同于Abort只是支持自定义code和error如果你使用gin.Default()来创建引擎,你会发现错误日志会被记录下来

  • func (c *Context) AbortWithStatus(code int) ////等同于Abort只是支持自定义code

  • func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) //等同于Abort只是返回的为json格式数据,多用于开发api时使用

以上今天针对gin 框架的源码阅读的学习记录。希望通过源码的阅读可以提升对于 golang 更进一步的深入理解。

总结

上一章我们说过其实 golang 本身的net/http 已经很简洁了。但是为啥我们使用框架,这一章我们就可以很清晰的看出来,gin 对于HTTP Request 和 HTTP Response 封装是很丰富精彩的。gin context 其实就是把request和response 做一个结构管理,可以通过 golang 结构体统一管理。

关于golang gin 学习系列,请点击关注

文章来源:智云一二三科技

文章标题:golang gin Context结构解读 学习系列(二)

文章地址:https://www.zhihuclub.com/86526.shtml

关于作者: 智云科技

热门文章

网站地图