溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

golang iris的使用方法

發(fā)布時間:2021-07-02 15:16:55 來源:億速云 閱讀:246 作者:chen 欄目:編程語言

這篇文章主要講解了“golang iris的使用方法”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“golang iris的使用方法”吧!

安裝iris
go get github.com/kataras/iris
實例
注冊一個route到服務(wù)的API
app := iris.New()

app.Handle("GET", "/ping", func(ctx iris.Context) {
    ctx.JSON(iris.Map{"message": "pong"})
})

app.Run(iris.Addr(":8080"))

幾行代碼就可以實現(xiàn),通過瀏覽器訪問http://localhost:8080/ping會返回{"message":"pong"}

使用Handle函數(shù)可以注冊方法,路徑和對應(yīng)的處理函數(shù)

添加middleware

如果我們希望記錄下所有的請求的log信息還希望在調(diào)用相應(yīng)的route時確認(rèn)請求的UA是否是我們允許的可以通過Use函數(shù)添加相應(yīng)的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的使用方法

使用postman訪問在Header中添加User-Agent訪問/ping可以正常返回結(jié)果,如果去掉User-Agent則會返回我們設(shè)定的"No authorized for ping"。因為我們添加了iris的log middleware所以在訪問時會在終端顯示相應(yīng)的log信息

取得請求參數(shù),展示到html

bookinfo.html

<html>
    <head>Book information</head>
    <body>
        <h3>{{ .bookName }}</h3>
        <h2>{{ .bookID }}</h2>
        <h2>{{ .author }}</h2>
        <h2>{{ .chapterCount }}</h2>
    </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"))
}

取得請求中帶的參數(shù)

ctx.Params().GetString("bookid")

設(shè)置html中變量的值

ctx.ViewData(key, value)

route允許和禁止外部訪問

實際使用中有時會有些route只能內(nèi)部使用,對外訪問不到。
可以通過使用 XXX_route.Method = iris.MethodNone設(shè)定為offline
內(nèi)部調(diào)用通過使用函數(shù) 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處理函數(shù)中會執(zhí)行 ctx.Exec("GET", "/magicapi")調(diào)用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已經(jīng)可以對外訪問了

grouping route

在實際應(yīng)用中會根據(jù)實際功能進行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("<h2>Calling bookInfoHandler </h2>")
    ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))
    ctx.Next()
}

func chapterListHandler(ctx iris.Context) {
    ctx.HTML("<h2>Calling chapterListHandler </h2>")
    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認(rèn)證。認(rèn)證方式是username和password。

在postman中訪問 http://localhost:8080/books/sfsg3234/bookinfo
設(shè)定Authorization為Basic Auth,Username和Password設(shè)定為程序中的值,訪問會正確回復(fù)。否則會回復(fù)Unauthorized
golang iris的使用方法

感謝各位的閱讀,以上就是“golang iris的使用方法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對golang iris的使用方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI