这里是 iris.Context 提供的完整的方法列表。
type (BodyDecoder interface {Decode(data []byte) error}Unmarshaler interface {Unmarshal(data []byte, outPtr interface{}) error}UnmarshalerFunc func(data []byte, outPtr interface{}) error)func (u UnmarshalerFunc) Unmarshal(data []byte, v interface{}) error {return u(data, v)}
BodyDecoder:BodyDecoder是一个接口,任何结构体都可以实现,以便于实现自定义读取JSON或者XML的 decode 行为。
一个简单的例子:
type User struct { Username string }func (u *User) Decode(data []byte) error {return json.Unmarshal(data, u)}
context.ReadJSON/ReadXML(&User{})将会调用User的Decode来解码请求体- 记住:这是完全可选的,默认的ReadJSON解码器是
encoding/json,ReadXML解码器是encoding/xml
Unmarshaler- 这是一个接口,实现了可以反序列化任何类型的原始数据。
- 提示:任何值的指针实现了
BodyDecoder将会覆写unmarshaler。
UnmarshalerFuncUnmarahsler接口的快捷方式- 更多详情看
Unmarshaler和BodyDecoder
Unmarshal- 解析
x-encoded的数据,并将结构存储到v指向的指针中。 Unmarshal使用与Marshal使用的相反的编码,必须为map,slice和指针。
- 解析
Context是一个客户端在服务器的 “中间人对象”。一个新的Context是从每一个连接的一个sync.Pool中获取的。Context是 Iris 的HTTP流上最重要的东西。开发者通过一个Context发送客户端请求的响应。开发者也从Context中获取客户端请求的信息。
type Context interface {BeginRequest(http.ResponseWriter, *http.Request)EndRequest()ResetResponseWriter(ResponseWriter)Request() *http.RequestResetRequest(r *http.Request)SetCurrentRouteName(currentRouteName string)GetCurrentRoute() RouteReadOnlyDo(Handlers)AddHandler(...Handler)SetHandlers(Handlers)Handlers() HandlersHandlerIndex(n int) (currentIndex int)Proceed(Handler) boolHandlerName() stringHandlerFileLine() (file string, line int)RouteName() stringNext()NextOr(handlers ...Handler) boolNextOrNotFound() boolNextHandler() HandlerSkip()StopExecution()IsStopped() boolOnConnectionClose(fnGoroutine func()) boolOnClose(cb func())Params() *RequestParamsValues() *memstore.StoreTranslate(format string, args ...interface{}) stringMethod() stringPath() stringRequestPath(escape bool) stringHost() stringSubdomain() (subdomain string)IsWWW() boolFullRequestURI() stringRemoteAddr() stringGetHeader(name string) stringIsAjax() boolIsMobile() boolGetReferrer() ReferrerHeader(name string, value string)ContentType(cType string)GetContentType() stringGetContentTypeRequested() stringGetContentLength() int64StatusCode(statusCode int)GetStatusCode() intRedirect(urlToRedirect string, statusHeader ...int)URLParamExists(name string) boolURLParamDefault(name string, def string) stringURLParam(name string) stringURLParamTrim(name string) stringURLParamEscape(name string) stringURLParamInt(name string) (int, error)URLParamIntDefault(name string, def int) intURLParamInt32Default(name string, def int32) int32URLParamInt64(name string) (int64, error)URLParamInt64Default(name string, def int64) int64URLParamFloat64(name string) (float64, error)URLParamFloat64Default(name string, def float64) float64URLParamBool(name string) (bool, error)URLParams() map[string]stringFormValueDefault(name string, def string) stringFormValue(name string) stringFormValues() map[string][]stringPostValueDefault(name string, def string) stringPostValue(name string) stringPostValueTrim(name string) stringPostValueInt(name string) (int, error)PostValueIntDefault(name string, def int) intPostValueInt64(name string) (int64, error)PostValueInt64Default(name string, def int64) int64PostValueFloat64(name string) (float64, error)PostValueFloat64Default(name string, def float64) float64PostValueBool(name string) (bool, error)PostValues(name string) []stringFormFile(key string) (multipart.File, *multipart.FileHeader, error)UploadFormFiles(destDirectory string, before ...func(Context, *multipart.FileHeader)) (n int64, err error)NotFound()SetMaxRequestBodySize(limitOverBytes int64)GetBody() ([]byte, error)UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) errorReadJSON(jsonObjectPtr interface{}) errorReadXML(xmlObjectPtr interface{}) errorReadForm(formObject interface{}) errorReadQuery(ptr interface{}) errorWrite(body []byte) (int, error)Writef(format string, args ...interface{}) (int, error)WriteString(body string) (int, error)SetLastModified(modtime time.Time)CheckIfModifiedSince(modtime time.Time) (bool, error)WriteNotModified()WriteWithExpiration(body []byte, modtime time.Time) (int, error)StreamWriter(writer func(w io.Writer) bool)ClientSupportsGzip() boolWriteGzip(b []byte) (int, error)TryWriteGzip(b []byte) (int, error)GzipResponseWriter() *GzipResponseWriterGzip(enable bool)ViewLayout(layoutTmplFile string)ViewData(key string, value interface{})GetViewData() map[string]interface{}View(filename string, optionalViewModel ...interface{}) errorBinary(data []byte) (int, error)Text(format string, args ...interface{}) (int, error)HTML(format string, args ...interface{}) (int, error)JSON(v interface{}, options ...JSON) (int, error)JSONP(v interface{}, options ...JSONP) (int, error)XML(v interface{}, options ...XML) (int, error)Markdown(markdownB []byte, options ...Markdown) (int, error)YAML(v interface{}) (int, error)ServeContent(content io.ReadSeeker, filename string, modtime time.Time, gzipCompression bool) errorServeFile(filename string, gzipCompression bool) errorSendFile(filename string, destinationName string) errorSetCookie(cookie *http.Cookie, options ...CookieOption)SetCookieKV(name, value string, options ...CookieOption)GetCookie(name string, options ...CookieOption) stringRemoveCookie(name string, options ...CookieOption)VisitAllCookies(visitor func(name string, value string))MaxAge() int64Record()Recorder() *ResponseRecorderIsRecording() (*ResponseRecorder, bool)BeginTransaction(pipe func(t *Transaction))SkipTransactions()TransactionsSkipped() boolExec(method, path string)RouteExists(method, path string) boolApplication() ApplicationString() string}
BeginRequest(http.ResponseWriter, *http.Request)- `BeginRequest` 对每个请求执行一次。
- 它为新来的请求准备
context(新的或者从pool获取) 的字段。 为了遵守 Iris 的流程,开发者应该:
1. 将处理器重置为 `nil`2. 将值重置为空3. 将session重置为 `nil`4. 将响应writer重置为 `http.ResponseWriter`5. 将请求重置为 `*http.Request`
- 其他可选的步骤,视开发的应用程序类型而定
BeginRequest(http.ResponseWriter, *http.Request)- 当发送完响应后执行一次,当前的 `context` 无用或者释放。
- 为了遵守 Iris 的流程,开发者应该:
- 刷新响应 writer 的结果
- 释放响应 writer
- 其他可选的步骤,视开发的应用程序类型而定
ResponseWriter() ResponseWriter- 预期返回与 response writer 兼容的 `http.ResponseWriter`
ResetResponseWriter(ResponseWriter)- 升级或者修改 `Context` 的 `ResponseWriter`
Request() *http.Request- 按预期返回原始的 `*http.Request`
ResetRequest(r *http.Request)- 设置 `Context` 的 `Request`
通过标准的
*http.Request的WithContext方法创建的新请求存储到iris.Context中很有用。当你出于某种愿意要对
*http.Request完全覆写时,使用ResetRequest。记住,当你只想改变一些字段的时候,你可以使用
Request(),它返回一个 Request 的指针,因此在没有完全覆写的情况下,改变也是用效的。用法:你使用原生的 http 处理器,它使用的是标准库
context来替代iris.Context.Values,从而获取值。r := ctx.Request()stdCtx := context.WithValue(r.Context(), key, val)ctx.ResetRequest(r.WithContext(stdCtx)).
SetCurrentRouteName(currentRouteName string)- `SetCurrentRouteName` 在内部设置 route 的名字, 目的是为了开发人员调用 `GetCurrentRoute()` 函数时能找到正确的当前的 `只读` 路由。
- 它被路由器初始化,如果你手动改变名字,除了通过
GetCurrentRoute()函数你将会获取到别的 route 之外,没有什么其它影响。 - 此外,要在该 context 执行不同路径的处理器,你应该使用
Exec函数,或者通过SetHandlers/AddHandler函数改变头部信息。
GetCurrentRoute() RouteReadOnly- 返回被这个请求路径注册的只读的路由。
