golang iris使用

7787 ワード

インストールiris
go get github.com/kataras/iris

≪インスタンス|Instance|emdw≫
サービスに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()
}

golang iris使用_第1张图片
Postmanアクセスを使用してHeaderにUser-Agentアクセス/pingを追加すると、結果が正常に返され、User-Agentを削除すると、設定した「No authorized for ping」が返されます.irisのlog middlewareを追加したので、アクセス時に端末に対応するlog情報が表示されます
リクエストパラメータを取得しhtmlに表示
bookinfo.html

    Book information
    
        

{{ .bookName }}

{{ .bookID }}

{{ .author }}

{{ .chapterCount }}


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("
Changed magicapi to %s
", state) } else { ctx.Writef("
Setting state incorrect(\"on\" or \"off\")
") } } }) 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
実際のアプリケーションでは、users、books、communityなど、実際の機能に基づいてrouteの分類が行われます./users/getuserdetail/users/getusercharges/users/getuserhistory
/books/bookinfo/books/chapterlist
このようなrouteについてはusersのgroupとbooksのgroupに分けることができます.このグループには共通のhandler処理があります共通の処理があります
package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/middleware/basicauth"
)

func bookInfoHandler(ctx iris.Context) {
    ctx.HTML("

Calling bookInfoHandler

") ctx.HTML("
bookID:" + ctx.Params().Get("bookID")) ctx.Next() } func chapterListHandler(ctx iris.Context) { ctx.HTML("

Calling chapterListHandler

") ctx.HTML("
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グループにアクセスするすべてのroutesに対してauth認証を先に行います.認証方式はusernameとpasswordです.
postmanでのアクセスhttp://localhost:8080/books/sfsg 3234/bookinfo設定AuthorizationをBasic Auth、UsernameとPasswordをプログラムの値に設定すると、アクセスが正しく返信されます.それ以外の場合はUnauthorized golang iris使用_第2张图片に返信されます