具名参数
具名参数只是您的路由的自定义路径,您可以在上下文语境中使用具名参数访问它所表示的路由。
// Param returns the string representation of the key's path named parameter's value
Param(key string) string
// ParamDecoded returns a url-query-decoded path parameter's value
ParamDecoded(key string) string
// ParamInt returns the int representation of the key's path named parameter's value
ParamInt(key string) (int, error)
// ParamInt64 returns the int64 representation of the key's path named parameter's value
ParamInt64(key string) (int64, error)
路径的长度没有限制。
使用
package main
import (
"strconv"
"github.com/kataras/iris"
)
func main() {
// Matches /hello/iris, (if PathCorrection:true match also /hello/iris/)
// Doesn't match /hello or /hello/ or /hello/iris/something
iris.Get("/hello/:name", func(ctx *iris.Context) {
// Retrieve the parameter name
name := ctx.Param("name")
ctx.Writef("Hello %s", name)
})
// Matches /profile/iris/friends/1, (if PathCorrection:true match also /profile/iris/friends/1/)
// Doesn't match /profile/ or /profile/iris
// Doesn't match /profile/iris/friends or /profile/iris/friends
// Doesn't match /profile/iris/friends/2/something
iris.Get("/profile/:fullname/friends/:friendID", func(ctx *iris.Context) {
// Retrieve the parameters fullname and friendID
fullname := ctx.Param("fullname")
friendID, err := ctx.ParamInt("friendID")
if err != nil {
// Do something with the error
return
}
ctx.HTML(iris.StatusOK, "<b> Hello </b>"+fullname+"<b> with friends ID </b>"+strconv.Itoa(friendID))
})
// Route Example:
// /posts/:id and /posts/new conflict with each other for performance reasons and simplicity (dynamic value conficts with the static 'new').
// but if you need to have them you can do following:
iris.Get("/posts/*action", func(ctx *iris.Context) {
action := ctx.Param("action")
if action == "/new" {
// it's posts/new page
ctx.Writef("POSTS NEW")
} else {
ctx.Writef("OTHER POSTS")
// it's posts/:id page
//doSomething with the action which is the id
}
})
iris.Listen(":8080")
}
任意匹配
// Will match any request which's url prefix is "/anything/" and has content after that
// Matches /anything/whateverhere/whateveragain or /anything/blablabla
// ctx.Param("randomName") will be /whateverhere/whateveragain, blablabla
// Doesn't match /anything or /anything/ or /something
iris.Get("/anything/*randomName", func(ctx *iris.Context) { } )