关于golang:golang-iris使用

3次阅读

共计 4474 个字符,预计需要花费 12 分钟才能阅读完成。

装置 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 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 信息

获得申请参数,展现到 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 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

正文完
 0