詳解Golang Iris框架的基本使用
Iris介紹
編寫一次并在任何地方以最小的機(jī)器功率運(yùn)行,如Android、ios、Linux和Windows等。它支持Google Go,只需一個(gè)可執(zhí)行的服務(wù)即可在所有平臺(tái)。 Iris以簡單而強(qiáng)大的api而聞名。 除了Iris為您提供的低級訪問權(quán)限。 Iris同樣擅長MVC。 它是唯一一個(gè)擁有MVC架構(gòu)模式豐富支持的Go Web框架,性能成本接近于零。 Iris為您提供構(gòu)建面向服務(wù)的應(yīng)用程序的結(jié)構(gòu)。 用Iris構(gòu)建微服務(wù)很容易。
1. Iris框架
1.1 Golang框架
Golang常用框架有:Gin、Iris、Beego、Buffalo、Echo、Revel,其中Gin、Beego和Iris較為流行。Iris是目前流行Golang框架中唯一提供MVC支持(實(shí)際上Iris使用MVC性能會(huì)略有下降)的框架,并且支持依賴注入,使用入門簡單,能夠快速構(gòu)建Web后端,也是目前幾個(gè)框架中發(fā)展最快的,從2016年截止至目前總共有17.4k stars(Gin 35K stars)。
Iris is a fast, simple yet fully featured and very efficient web framework for Go. It provides a beautifully expressive and easy to use foundation for your next website or API.
1.2 安裝Iris
Iris官網(wǎng):https://iris-go.com/
Iris Github:https://github.com/kataras/iris
# go get -u -v 獲取包 go get github.com/kataras/iris/v12@latest # 可能提示@latest是錯(cuò)誤,如果版本大于11,可以使用下面打開GO111MODULE選項(xiàng) # 使用完最好關(guān)閉,否則編譯可能出錯(cuò) go env -w GO111MODULE=on # go get失敗可以更改代理 go env -w GOPROXY=https://goproxy.cn,direct
2. 使用Iris構(gòu)建服務(wù)端
2.1 簡單例子1——直接返回消息
package main import ( "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/middleware/logger" "github.com/kataras/iris/v12/middleware/recover" ) func main() { app := iris.New() app.Logger().SetLevel("debug") // 設(shè)置recover從panics恢復(fù),設(shè)置log記錄 app.Use(recover.New()) app.Use(logger.New()) app.Handle("GET", "/", func(ctx iris.Context) { ctx.HTML("<h1>Hello Iris!</h1>") }) app.Handle("GET", "/getjson", func(ctx iris.Context) { ctx.JSON(iris.Map{"message": "your msg"}) }) app.Run(iris.Addr("localhost:8080")) }
其他便捷設(shè)置方法:
// 默認(rèn)設(shè)置日志和panic處理 app := iris.Default()
我們可以看到iris.Default()的源碼:
// 注:默認(rèn)設(shè)置"./view"為html view engine目錄 func Default() *Application { app := New() app.Use(recover.New()) app.Use(requestLogger.New()) app.defaultMode = true return app }
2.2 簡單例子2——使用HTML模板
package main import "github.com/kataras/iris/v12" func main() { app := iris.New() // 注冊模板在work目錄的views文件夾 app.RegisterView(iris.HTML("./views", ".html")) app.Get("/", func(ctx iris.Context) { // 設(shè)置模板中"message"的參數(shù)值 ctx.ViewData("message", "Hello world!") // 加載模板 ctx.View("hello.html") }) app.Run(iris.Addr("localhost:8080")) }
上述例子使用的hello.html模板
<html> <head> <title>Hello Page</title> </head> <body> <h1>{{ .message }}</h1> </body> </html>
2.3 路由處理
上述例子中路由處理,可以使用下面簡單替換,分別針對HTTP中的各種方法
app.Get("/someGet", getting) app.Post("/somePost", posting) app.Put("/somePut", putting) app.Delete("/someDelete", deleting) app.Patch("/somePatch", patching) app.Head("/someHead", head) app.Options("/someOptions", options)
例如,使用路由“/hello”的Get路徑
app.Get("/hello", handlerHello) func handlerHello(ctx iris.Context) { ctx.WriteString("Hello") } // 等價(jià)于下面 app.Get("/hello", func(ctx iris.Context) { ctx.WriteString("Hello") })
2.4 使用中間件
app.Use(myMiddleware) func myMiddleware(ctx iris.Context) { ctx.Application().Logger().Infof("Runs before %s", ctx.Path()) ctx.Next() }
2.5 使用文件記錄日志
整個(gè)Application使用文件記錄
上述記錄日志
// 獲取當(dāng)前時(shí)間 now := time.Now().Format("20060102") + ".log" // 打開文件,如果不存在創(chuàng)建,如果存在追加文件尾,權(quán)限為:擁有者可讀可寫 file, err := os.OpenFile(now, os.O_CREATE | os.O_APPEND, 0600) defer file.Close() if err != nil { app.Logger().Errorf("Log file not found") } // 設(shè)置日志輸出為文件 app.Logger().SetOutput(file)
到文件可以和中間件結(jié)合,以控制不必要的調(diào)試信息記錄到文件
func myMiddleware(ctx iris.Context) { now := time.Now().Format("20060102") + ".log" file, err := os.OpenFile(now, os.O_CREATE | os.O_APPEND, 0600) defer file.Close() if err != nil { ctx.Application().Logger().SetOutput(file).Errorf("Log file not found") os.Exit(-1) } ctx.Application().Logger().SetOutput(file).Infof("Runs before %s", ctx.Path()) ctx.Next() }
上述方法只能打印Statuscode為200的路由請求,如果想要打印其他狀態(tài)碼請求,需要另使用
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) { now := time.Now().Format("20060102") + ".log" file, err := os.OpenFile(now, os.O_CREATE | os.O_APPEND, 0600) defer file.Close() if err != nil { ctx.Application().Logger().SetOutput(file).Errorf("Log file not found") os.Exit(-1) } ctx.Application().Logger().SetOutput(file).Infof("404") ctx.WriteString("404 not found") })
Iris有十分強(qiáng)大的路由處理程序,你能夠按照十分靈活的語法設(shè)置路由路徑,并且如果沒有涉及正則表達(dá)式,Iris會(huì)計(jì)算其需求預(yù)先編譯索引,用十分小的性能消耗來完成路由處理。
注:ctx.Params()和ctx.Values()是不同的,下面是官網(wǎng)給出的解釋:
Path parameter's values can be retrieved from ctx.Params()Context's local storage that can be used to communicate between handlers and middleware(s) can be stored to ctx.Values() .
Iris可以使用的參數(shù)類型
Param Type | Go Type | Validation | Retrieve Helper |
---|---|---|---|
:string | string | anything (single path segment) | Params().Get |
:int | int | -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch | Params().GetInt |
:int8 | int8 | -128 to 127 | Params().GetInt8 |
:int16 | int16 | -32768 to 32767 | Params().GetInt16 |
:int32 | int32 | -2147483648 to 2147483647 | Params().GetInt32 |
:int64 | int64 | -9223372036854775808 to 92233720368?4775807 | Params().GetInt64 |
:uint | uint | 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host arch | Params().GetUint |
:uint8 | uint8 | 0 to 255 | Params().GetUint8 |
:uint16 | uint16 | 0 to 65535 | Params().GetUint16 |
:uint32 | uint32 | 0 to 4294967295 | Params().GetUint32 |
:uint64 | uint64 | 0 to 18446744073709551615 | Params().GetUint64 |
:bool | bool | “1” or “t” or “T” or “TRUE” or “true” or “True” or “0” or “f” or “F” or “FALSE” or “false” or “False” | Params().GetBool |
:alphabetical | string | lowercase or uppercase letters | Params().Get |
:file | string | lowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenames | Params().Get |
:path | string | anything, can be separated by slashes (path segments) but should be the last part of the route path | Params().Get |
在路徑中使用參數(shù)
app.Get("/users/{id:uint64}", func(ctx iris.Context){ id := ctx.Params().GetUint64Default("id", 0) })
使用post傳遞參數(shù)
app.Post("/login", func(ctx iris.Context) { username := ctx.FormValue("username") password := ctx.FormValue("password") ctx.JSON(iris.Map{ "Username": username, "Password": password, }) })
以上就是Iris的基本入門使用,當(dāng)然還有更多其他操作:中間件使用、正則表達(dá)式路由路徑的使用、Cache、Cookie、Session、File Server、依賴注入、MVC等的用法,可以參照官方教程使用,后期有時(shí)間會(huì)寫文章總結(jié)。
到此這篇關(guān)于詳解Golang Iris框架的基本使用的文章就介紹到這了,更多相關(guān)Golang Iris框架使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Goland使用Go Modules創(chuàng)建/管理項(xiàng)目的操作
這篇文章主要介紹了Goland使用Go Modules創(chuàng)建/管理項(xiàng)目的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05Golang中的select語句及其應(yīng)用實(shí)例
本文將介紹Golang中的select語句的使用方法和作用,并通過代碼示例展示其在并發(fā)編程中的實(shí)際應(yīng)用,此外,還提供了一些與select相關(guān)的面試題,幫助讀者更好地理解和應(yīng)用select語句2023-12-12Go select 死鎖的一個(gè)細(xì)節(jié)
這篇文章主要給大家分享的是Go select 死鎖的一個(gè)細(xì)節(jié),文章先是對主題提出問題,然后展開內(nèi)容,感興趣的小伙伴可以借鑒一下,希望對你有所幫助2021-10-10解決Golang中ResponseWriter的一個(gè)坑
這篇文章主要介紹了解決Golang中ResponseWriter的一個(gè)坑,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04利用ChatGPT編寫一個(gè)Golang圖像壓縮函數(shù)
這篇文章主要為大家詳細(xì)介紹了如何利用ChatGPT幫我們寫了一個(gè)Golang圖像壓縮函數(shù),文中的示例代碼簡潔易懂,感興趣的小伙伴可以嘗試一下2023-04-04