GoWeb開發_Iris框架講解(三):路由功能處理方式

Context概念

Context是iris框架中的一個路由上下文對象,在iris框架中的源碼路徑定義爲:{$goPath}\github.com\kataras\iris\context\context.go。如下是Context的聲明和定義: html

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的相關用法。學習者bugit

正則表達式路由

Iris框架在進行處理http請求時,支持請求url中包含正則表達式。 正則表達式的具體規則爲: github

  • 一、使用{}對增則表達式進行包裹,url中出現相似{}樣式的格式,即識別爲正則表達式 正則表達式

  • 二、支持自定義增則表達式的變量的命名,變量名用字母表示。好比:{name} api

  • 三、支持對自定義正則表達式變量的數據類型限制,變量名和對應的數據類型之間用「:」分隔開。好比:{name:string}表示增則表達式爲name,類型限定爲string類型bash

  • 四、經過context.Params()的Get()和GetXxx()系列方法來獲取對應的請求url中的增則表達式的變量markdown

  • 五、增則表達式支持變量的數據類型包括:string、int、uint、bool等app

以下是正則表達式的請求示例: 框架

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請求dom

相關文章
相關標籤/搜索