自定义验证器

未匹配的标注

本节有点长,自定义验证器,像内置的路径参数验证一样运作

自己动手干

字符串参数

RegisterFunc 接收一个返回 func(paramValue string) bool 类型的任意函数。或者仅仅只是func(string) bool类型。如果验证失败,它将触发404或 else 关键字具有的任何状态码。

latLonExpr := "^-?[0-9]{1,3}(?:\\.[0-9]{1,10})?$"
latLonRegex, _ := regexp.Compile(latLonExpr)

// 注册一个自定义的无参宏( macro) 函数,获取一个 :string 参数类型.
// 所使用正则的MatchString 方法是一个  func(string) bool 函数类型, 用它本来的样子就好了
app.Macros().Get("string").RegisterFunc("coordinate", latLonRegex.MatchString)

app.Get("/coordinates/{lat:string coordinate()}/{lon:string coordinate()}", func(ctx iris.Context) {
    ctx.Writef("Lat: %s | Lon: %s", ctx.Params().Get("lat"), ctx.Params().Get("lon"))
})

整形参数

注册自定义宏函数接收两个整形参数

app.Macros().Get("string").RegisterFunc("range", func(minLength, maxLength int) func(string) bool {
    return func(paramValue string) bool {
        return len(paramValue) >= minLength && len(paramValue) <= maxLength
    }
})

app.Get("/limitchar/{name:string range(1,200) else 400}", func(ctx iris.Context) {
    name := ctx.Params().Get("name")
    ctx.Writef(`Hello %s | the name should be between 1 and 200 characters length
    otherwise this handler will not be executed`, name)
})

字符串切片参数

注册自定义宏函数接收任意个字符串类型参数

app.Macros().Get("string").RegisterFunc("has", func(validNames []string) func(string) bool {
    return func(paramValue string) bool {
        for _, validName := range validNames {
            if validName == paramValue {
                return true
            }
        }
        return false
    }
})

app.Get("/static_validation/{name:string has([kataras,gerasimos,maropoulos])}", func(ctx iris.Context) {
    name := ctx.Params().Get("name")
    ctx.Writef(`Hello %s | the name should be "kataras" or "gerasimos" or "maropoulos"
    otherwise this handler will not be executed`, name)
})

示例

func main() {
    app := iris.Default()

    // 匹配 /user/john 但不会匹配 /user/ 或  /user.
    app.Get("/user/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        ctx.Writef("Hello %s", name)
    })

    // 匹配 /users/42
    // 但不会匹配 /users/-1 因 uint 类型应大于0
    // 同样不会匹配 /users 或 /users/.
    app.Get("/users/{id:uint64}", func(ctx iris.Context) {
        id := ctx.Params().GetUint64Default("id", 0)
        ctx.Writef("User with ID: %d", id)
    })

    // 不管怎样, 将匹配 /user/john/send , 也可匹配  /user/john/everything/else/here
    // 但不会匹配 /user/john 也不会匹配 /user/john/.
    app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        action := ctx.Params().Get("action")
        message := name + " is " + action
        ctx.WriteString(message)
    })

    app.Run(iris.Addr(":8080"))
}

若未指定参数类型将默认使用string,因此 {name:string} 与 {name}效果是完全一样地。

学习更多的关于路径参数类型请移步 这儿.

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

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


暂无话题~