handle请求以及路由匹配

未匹配的标注

直接上代码吧,更加直观:

package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
)

func main(){
    app := iris.New()
    //1.handle方式处理get请求
    app.Handle("GET","/userInfo", func(context context.Context) {
        path := context.Path()
        app.Logger().Info(path) //info级别的打印到控制台
        app.Logger().Error("request path:" + path)  // error级别的打印到当前控制台
    })
    //2.handle方式处理post请求
    app.Handle("POST","postInfo", func(context context.Context) {
        path := context.Path()
        app.Logger().Info(path)
        context.HTML(path)
    })
    //3.get正则路由匹配
    //http://localhost:8001/weather/2020-01-02/beijing
    //http://localhost:8001/weather/2020-02-04/jinan
    //就跟上边的路由一样我们不可能每个都写那么一个get请求  所以可以改成路由匹配的形式来搞
    app.Get("/weather/{date}/{city}", func(context context.Context) {
        path := context.Path()
        date := context.Params().Get("date")  //获取请求路径里面的参数的值
        city := context.Params().Get("city")  //获取请求路径里面的参数的值
        context.WriteString(path + "----" + date + "----" + city)
    })

    //3.1get正则路由匹配当中你还可以设置参数的类型 类型匹配不会也会报错失败
    app.Get("/goods/{date:int64}/{city:string}", func(context context.Context) {
        path := context.Path()
        date := context.Params().Get("date")  //获取请求路径里面的参数的值
        city := context.Params().Get("city")  //获取请求路径里面的参数的值
        context.WriteString(path + "----" + date + "----" + city)
    })


    app.Run(iris.Addr(":8011"),iris.WithoutServerError(iris.ErrServerClosed))
}

Context概念

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请求

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~