搜尋
首頁後端開發Golang解析golang iris怎麼使用

解析golang iris怎麼使用

Jul 02, 2021 pm 02:02 PM
golang

安裝iris

<span style="font-size: 14px;">go get github.com/kataras/iris<br></span>

##實例

##註冊一個route到服務的API
<span style="font-size: 14px;">app := iris.New()<br><br>app.Handle("GET", "/ping", func(ctx iris.Context) {<br>    ctx.JSON(iris.Map{"message": "pong"})<br>})<br><br>app.Run(iris.Addr(":8080"))<br></span>
幾行程式碼就可以實現,透過瀏覽器存取http://localhost :8080/ping會回傳{"message":"pong"}

#使用Handle函數可以註冊方法,路徑和對應的處理函數

#新增middleware
如果我們希望記錄下所有的請求的log資訊也希望在呼叫對應的route時確認請求的UA是否是我們允許的可以透過Use函數來新增對應的middleware

<span style="font-size: 14px;">package main<br/><br/>import (<br/>    "github.com/kataras/iris"<br/>    "github.com/kataras/iris/middleware/logger"<br/>)<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    app.Use(logger.New())<br/>    app.Use(checkAgentMiddleware)<br/><br/>    app.Handle("GET", "/ping", func(ctx iris.Context) {<br/>        ctx.JSON(iris.Map{"message": "pong"})<br/>    })<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/><br/>func checkAgentMiddleware(ctx iris.Context) {<br/>    ctx.Application().Logger().Infof("Runs before %s", ctx.Path())<br/>    user_agent := ctx.GetHeader("User-Agent")<br/><br/>    if user_agent != "pingAuthorized" {<br/>        ctx.JSON("No authorized for ping")<br/>        return<br/>    }<br/>    ctx.Next()<br/>}<br/></span>

解析golang iris怎麼使用

使用postman存取在Header中新增User-Agent存取/ping可以正常回傳結果,如果去掉User-Agent則會傳回我們設定的"No authorized for ping"。因為我們加入了iris的log middleware所以在存取時會在終端機顯示對應的log資訊

取得請求參數,展示到html
bookinfo.html

<span style="font-size: 14px;"><html><br/>    <head>Book information</head><br/>    <body><br/>        <h2 id="nbsp-bookName-nbsp">{{ .bookName }}</h2><br/>        <h1 id="nbsp-bookID-nbsp">{{ .bookID }}</h1><br/>        <h1 id="nbsp-author-nbsp">{{ .author }}</h1><br/>        <h1 id="nbsp-chapterCount-nbsp">{{ .chapterCount }}</h1><br/>    </body><br/></html><br/></span>

main.go

#

<span style="font-size: 14px;">package main<br/><br/>import "github.com/kataras/iris"<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    app.RegisterView(iris.HTML("./views", ".html"))<br/><br/>    app.Handle("GET", "/bookinfo/{bookid:string}", func(ctx iris.Context) {<br/>        bookID := ctx.Params().GetString("bookid")<br/><br/>        ctx.ViewData("bookName", "Master iris")<br/>        ctx.ViewData("bookID", bookID)<br/>        ctx.ViewData("author", "Iris expert")<br/>        ctx.ViewData("chapterCount", "40")<br/><br/>        ctx.View("bookinfo.html")<br/>    })<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/></span>

取得請求中帶的參數


ctx.Params().GetString("bookid")
設定html中變數的值

ctx.ViewData(key, value)

route允許和禁止外部存取

實際使用中有時會有些route只能內部使用,對外訪問不到。

可以透過使用XXX_route.Method = iris.MethodNone設定為offline內部呼叫透過使用函數Context.Exec("NONE", "/XXX_yourroute")

# main.go

<span style="font-size: 14px;">package main<br/><br/>import "github.com/kataras/iris"<br/><br/>import "strings"<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    magicAPI := app.Handle("NONE", "/magicapi", func(ctx iris.Context) {<br/>        if ctx.GetCurrentRoute().IsOnline() {<br/>            ctx.Writef("I&#39;m back!")<br/>        } else {<br/>            ctx.Writef("I&#39;ll be back")<br/>        }<br/>    })<br/><br/>    app.Handle("GET", "/onoffhandler/{method:string}/{state:string}", func(ctx iris.Context) {<br/>        changeMethod := ctx.Params().GetString("method")<br/>        state := ctx.Params().GetString("state")<br/><br/>        if changeMethod == "" || state == "" {<br/>            return<br/>        }<br/><br/>        if strings.Index(magicAPI.Path, changeMethod) == 1 {<br/>            settingState := strings.ToLower(state)<br/>            if settingState == "on" || settingState == "off" {<br/>                if strings.ToLower(state) == "on" && !magicAPI.IsOnline() {<br/>                    magicAPI.Method = iris.MethodGet<br/>                } else if strings.ToLower(state) == "off" && magicAPI.IsOnline() {<br/>                    magicAPI.Method = iris.MethodNone<br/>                }<br/><br/>                app.RefreshRouter()<br/><br/>                ctx.Writef("\n Changed magicapi to %s\n", state)<br/>            } else {<br/>                ctx.Writef("\n Setting state incorrect(\"on\" or \"off\") \n")<br/>            }<br/><br/>        }<br/>    })<br/><br/>    app.Handle("GET", "/execmagicapi", func(ctx iris.Context) {<br/>        ctx.Values().Set("from", "/execmagicapi")<br/><br/>        if !magicAPI.IsOnline() {<br/>            ctx.Exec("NONE", "/magicapi")<br/>        } else {<br/>            ctx.Exec("GET", "/magicapi")<br/>        }<br/>    })<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/></span>

測試:


<1>访问http://localhost:8080/magicapi,返回Not found。说明route magicapi对外无法访问
<2>访问http://localhost:8080/execmagicapi,返回I&#39;ll be back。在execmagicapi处理函数中会执行 ctx.Exec("GET", "/magicapi")调用offline的route magicapi。在magicapi中会判断自己是否offline,如果为offline则返回I&#39;ll be back。
<3>访问http://localhost:8080/onoffhandler/magicapi/on改变magicapi为online
<4>再次访问http://localhost:8080/magicapi,返回I&#39;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處理共同的一些處理

<span style="font-size: 14px;">package main<br/><br/>import (<br/>    "time"<br/><br/>    "github.com/kataras/iris"<br/>    "github.com/kataras/iris/middleware/basicauth"<br/>)<br/><br/>func bookInfoHandler(ctx iris.Context) {<br/>    ctx.HTML("<h1 id="Calling-nbsp-bookInfoHandler-nbsp">Calling bookInfoHandler </h1>")<br/>    ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))<br/>    ctx.Next()<br/>}<br/><br/>func chapterListHandler(ctx iris.Context) {<br/>    ctx.HTML("<h1 id="Calling-nbsp-chapterListHandler-nbsp">Calling chapterListHandler </h1>")<br/>    ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))<br/>    ctx.Next()<br/>}<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    authConfig := basicauth.Config{<br/>        Users:   map[string]string{"bookuser": "testabc123"},<br/>        Realm:   "Authorization required",<br/>        Expires: time.Duration(30) * time.Minute,<br/>    }<br/><br/>    authentication := basicauth.New(authConfig)<br/><br/>    books := app.Party("/books", authentication)<br/><br/>    books.Get("/{bookID:string}/bookinfo", bookInfoHandler)<br/>    books.Get("/chapterlist/{bookID:string}", chapterListHandler)<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/></span>

上例中使用了basicauth。所有造訪books group的routes都會先做auth認證。認證方式是username和password。

在postman中存取http://localhost:8080/books/sfsg3234/bookinfo

設定Authorization為Basic Auth,Username和Password設定為程式中的值,訪問會正確回應。否則會回覆Unauthorized

解析golang iris怎麼使用

更多golang相關技術文章,請造訪

##golang#教學列!

以上是解析golang iris怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
初始功能和副作用:平衡初始化與可維護性初始功能和副作用:平衡初始化與可維護性Apr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

開始GO:初學者指南開始GO:初學者指南Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

進行並發模式:開發人員的最佳實踐進行並發模式:開發人員的最佳實踐Apr 26, 2025 am 12:20 AM

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。

進行生產:現實世界的用例和示例進行生產:現實世界的用例和示例Apr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

go中的自定義錯誤類型:提供詳細的錯誤信息go中的自定義錯誤類型:提供詳細的錯誤信息Apr 26, 2025 am 12:09 AM

我們需要自定義錯誤類型,因為標準錯誤接口提供的信息有限,自定義類型能添加更多上下文和結構化信息。 1)自定義錯誤類型能包含錯誤代碼、位置、上下文數據等,2)提高調試效率和用戶體驗,3)但需注意其複雜性和維護成本。

使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。