Context是iris框架中的一個路由上下文對象,在iris框架中的源碼路徑定義為:{$goPath}\github.com\kataras\iris\context\context.go。以下是Context的聲明和定義:
package context
type Context interface {
BeginRequest(http.ResponseWriter, *http.Request)
EndRequest()
ResponseWriter() ResponseWriter
ResetResponseWriter(ResponseWriter)
Request() *http.Request
SetCurrentRouteName(currentRouteName string)
GetCurrentRoute() RouteReadOnly
Do(Handlers)
AddHandler(...Handler)
SetHandlers(Handlers)
Handlers() Handlers
HandlerIndex(n int) (currentIndex int)
Proceed(Handler) bool
HandlerName() string
Next()
NextOr(handlers ...Handler) bool
NextOrNotFound() bool
NextHandler() Handler
Skip()
StopExecution()
IsStopped() bool
Params() *RequestParams
Values() *memstore.Store
Translate(format string, args ...interface{}) string
Method() string
Path() string
RequestPath(escape bool) string
Host() string
Subdomain() (subdomain string)
IsWWW() bool
RemoteAddr() string
GetHeader(name string) string
IsAjax() bool
IsMobile() bool
Header(name string, value string)
ContentType(cType string)
GetContentType() string
GetContentLength() int64
StatusCode(statusCode int)
GetStatusCode() int
Redirect(urlToRedirect string, statusHeader ...int)
URLParamExists(name string) bool
URLParamDefault(name string, def string) string
URLParam(name string) string
URLParamTrim(name string) string
URLParamEscape(name string) string
View(filename string, optionalViewModel ...interface{}) error
Text(text string) (int, error)
HTML(htmlContents string) (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)
......
在該Context的接口定義中,我們可以發現,包含很多處理請求及數據返回的操作。在iris框架內,提供給開發者一個ContextPool,即存儲上下文變量Context的管理池,該變量池中有多個context實例,可以進行復用。每次有新請求,就會獲取一個新的context變量實例,來進行請求的路由處理。我們在實際的案例學習中,會向大家展示關於Context的相關用法。學習者bu
正則表達式路由
Iris框架在進行處理http請求時,支持請求url中包含正則表達式。 正則表達式的具體規則為:
-
1、使用{}對增則表達式進行包裹,url中出現類似{}樣式的格式,即識別為正則表達式
-
2、支持自定義增則表達式的變量的命名,變量名用字母表示。比如:{name}
-
3、支持對自定義正則表達式變量的數據類型限制,變量名和對應的數據類型之間用“:”分隔開。比如:{name:string}表示增則表達式為name,類型限定為string類型
-
4、通過context.Params()的Get()和GetXxx()系列方法來獲取對應的請求url中的增則表達式的變量
-
5、增則表達式支持變量的數據類型包括:string、int、uint、bool等
如下是正則表達式的請求示例:
app.Get("/api/users/{isLogin:bool}", func(context context.Context) {
isLogin, err := context.Params().GetBool("isLogin")
if err != nil {
context.StatusCode(iris.StatusNonAuthoritativeInfo)
return
}
if isLogin {
context.WriteString(" 已登錄 ")
} else {
context.WriteString(" 未登錄 ")
}
})
中間件處理請求路由
當我們在iris框架中說起中間件的相關內容時,我們所討論和學習的是在HTTP請求