golang iris使用安装irisgo get github.com/kataras/iris
实例注册一个route到服务的apiapp := 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 main
import (
"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信息
取得请求参数,展示到htmlbookinfo.html
<html>
<head>book information</head>
<body>
<h2>{{ .bookname }}</h2>
<h1>{{ .bookid }}</h1>
<h1>{{ .author }}</h1>
<h1>{{ .chaptercount }}</h1>
</body>
</html>
main.go
package main
import "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 main
import "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 main
import (
"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
更多golang相关技术文章,请访问golang教程栏目!
以上就是解析golang iris怎么使用的详细内容。