装置iris
go get github.com/kataras/iris
实例
注册一个route到服务的API
app := iris.New()app.Handle("GET", "/ping", func(ctx iris.Context) { ctx.JSON(iris.Map{"message": "pong"})})app.Run(iris.Addr(":8080"))
几行代码就能够实现,通过浏览器拜访http://localhost:8080/ping会返回{"message":"pong"}
应用Handle函数能够注册办法,门路和对应的处理函数
增加middleware
如果咱们心愿记录下所有的申请的log信息还心愿在调用相应的route时确认申请的UA是否是咱们容许的能够通过Use函数增加相应的middleware
package mainimport ( "github.com/kataras/iris" "github.com/kataras/iris/middleware/logger")func main() { app := iris.New() app.Use(logger.New()) app.Use(checkAgentMiddleware) app.Handle("GET", "/ping", func(ctx iris.Context) { ctx.JSON(iris.Map{"message": "pong"}) }) app.Run(iris.Addr(":8080"))}func checkAgentMiddleware(ctx iris.Context) { ctx.Application().Logger().Infof("Runs before %s", ctx.Path()) user_agent := ctx.GetHeader("User-Agent") if user_agent != "pingAuthorized" { ctx.JSON("No authorized for ping") return } ctx.Next()}
应用postman拜访在Header中增加User-Agent拜访/ping能够失常返回后果,如果去掉User-Agent则会返回咱们设定的"No authorized for ping"。因为咱们增加了iris的log middleware所以在拜访时会在终端显示相应的log信息
获得申请参数,展现到html
bookinfo.html
<html> <head>Book information</head> <body> <h2>{{ .bookName }}</h2> <h1>{{ .bookID }}</h1> <h1>{{ .author }}</h1> <h1>{{ .chapterCount }}</h1> </body></html>
main.go
package mainimport "github.com/kataras/iris"func main() { app := iris.New() app.RegisterView(iris.HTML("./views", ".html")) app.Handle("GET", "/bookinfo/{bookid:string}", func(ctx iris.Context) { bookID := ctx.Params().GetString("bookid") ctx.ViewData("bookName", "Master iris") ctx.ViewData("bookID", bookID) ctx.ViewData("author", "Iris expert") ctx.ViewData("chapterCount", "40") ctx.View("bookinfo.html") }) app.Run(iris.Addr(":8080"))}
获得申请中带的参数
ctx.Params().GetString("bookid")
设置html中变量的值
ctx.ViewData(key, value)
route容许和禁止内部拜访
理论应用中有时会有些route只能外部应用,对外拜访不到。
能够通过应用 XXX_route.Method = iris.MethodNone设定为offline
外部调用通过应用函数 Context.Exec("NONE", "/XXX_yourroute")
main.go
package mainimport "github.com/kataras/iris"import "strings"func main() { app := iris.New() magicAPI := app.Handle("NONE", "/magicapi", func(ctx iris.Context) { if ctx.GetCurrentRoute().IsOnline() { ctx.Writef("I'm back!") } else { ctx.Writef("I'll be back") } }) app.Handle("GET", "/onoffhandler/{method:string}/{state:string}", func(ctx iris.Context) { changeMethod := ctx.Params().GetString("method") state := ctx.Params().GetString("state") if changeMethod == "" || state == "" { return } if strings.Index(magicAPI.Path, changeMethod) == 1 { settingState := strings.ToLower(state) if settingState == "on" || settingState == "off" { if strings.ToLower(state) == "on" && !magicAPI.IsOnline() { magicAPI.Method = iris.MethodGet } else if strings.ToLower(state) == "off" && magicAPI.IsOnline() { magicAPI.Method = iris.MethodNone } app.RefreshRouter() ctx.Writef("\n Changed magicapi to %s\n", state) } else { ctx.Writef("\n Setting state incorrect(\"on\" or \"off\") \n") } } }) app.Handle("GET", "/execmagicapi", func(ctx iris.Context) { ctx.Values().Set("from", "/execmagicapi") if !magicAPI.IsOnline() { ctx.Exec("NONE", "/magicapi") } else { ctx.Exec("GET", "/magicapi") } }) app.Run(iris.Addr(":8080"))}
测试:
<1>拜访http://localhost:8080/magicapi,返回Not found。阐明route magicapi对外无法访问
<2>拜访http://localhost:8080/execmagicapi,返回I'll be back。在execmagicapi处理函数中会执行 ctx.Exec("GET", "/magicapi")调用offline的route magicapi。在magicapi中会判断本人是否offline,如果为offline则返回I'll be back。
<3>拜访http://localhost:8080/onoffhandler/magicapi/on扭转magicapi为online
<4>再次拜访http://localhost:8080/magicapi,返回I'm back!。阐明route /mabicapi曾经能够对外拜访了
grouping route
在理论利用中会依据理论性能进行route的分类,例如users,books,community等。
/users/getuserdetail
/users/getusercharges
/users/getuserhistory
/books/bookinfo
/books/chapterlist
对于这类route能够把他们划分在users的group和books的group。对该group会有共通的handler解决独特的一些解决
package mainimport ( "time" "github.com/kataras/iris" "github.com/kataras/iris/middleware/basicauth")func bookInfoHandler(ctx iris.Context) { ctx.HTML("<h1>Calling bookInfoHandler </h1>") ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID")) ctx.Next()}func chapterListHandler(ctx iris.Context) { ctx.HTML("<h1>Calling chapterListHandler </h1>") ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID")) ctx.Next()}func main() { app := iris.New() authConfig := basicauth.Config{ Users: map[string]string{"bookuser": "testabc123"}, Realm: "Authorization required", Expires: time.Duration(30) * time.Minute, } authentication := basicauth.New(authConfig) books := app.Party("/books", authentication) books.Get("/{bookID:string}/bookinfo", bookInfoHandler) books.Get("/chapterlist/{bookID:string}", chapterListHandler) app.Run(iris.Addr(":8080"))}
上例中应用了basicauth。对所有拜访books group的routes都会先做auth认证。认证形式是username和password。
在postman中拜访 http://localhost:8080/books/sfsg3234/bookinfo
设定Authorization为Basic Auth,Username和Password设定为程序中的值,拜访会正确回复。否则会回复Unauthorized