詳解Golang Iris框架的基本使用
Iris介紹
編寫一次并在任何地方以最小的機(jī)器功率運(yùn)行,如Android、ios、Linux和Windows等。它支持Google Go,只需一個(gè)可執(zhí)行的服務(wù)即可在所有平臺(tái)。 Iris以簡(jiǎn)單而強(qiáng)大的api而聞名。 除了Iris為您提供的低級(jí)訪問(wèn)權(quán)限。 Iris同樣擅長(zhǎng)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ì)略有下降)的框架,并且支持依賴注入,使用入門簡(jiǎn)單,能夠快速構(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,可以使用下面打開(kāi)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 簡(jiǎn)單例子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 簡(jiǎn)單例子2——使用HTML模板
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
// 注冊(cè)模板在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 路由處理
上述例子中路由處理,可以使用下面簡(jiǎn)單替換,分別針對(duì)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"
// 打開(kāi)文件,如果不存在創(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的路由請(qǐng)求,如果想要打印其他狀態(tài)碼請(qǐng)求,需要另使用
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)大的路由處理程序,你能夠按照十分靈活的語(yǔ)法設(shè)置路由路徑,并且如果沒(méi)有涉及正則表達(dá)式,Iris會(huì)計(jì)算其需求預(yù)先編譯索引,用十分小的性能消耗來(lái)完成路由處理。
注: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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go語(yǔ)言K8S?的?informer機(jī)制淺析
這篇文章為大家主要介紹了go語(yǔ)言K8S?的?informer機(jī)制淺析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
GoLang基礎(chǔ)學(xué)習(xí)之go?test測(cè)試
相信每位編程開(kāi)發(fā)者們應(yīng)該都知道,Golang作為一門標(biāo)榜工程化的語(yǔ)言,提供了非常簡(jiǎn)便、實(shí)用的編寫單元測(cè)試的能力,下面這篇文章主要給大家介紹了關(guān)于GoLang基礎(chǔ)學(xué)習(xí)之go?test測(cè)試的相關(guān)資料,需要的朋友可以參考下2022-08-08
攔截信號(hào)Golang應(yīng)用優(yōu)雅關(guān)閉的操作方法
這篇文章主要介紹了攔截信號(hào)優(yōu)雅關(guān)閉Golang應(yīng)用,本文介紹了信號(hào)的概念及常用信號(hào),并給出了應(yīng)用廣泛的幾個(gè)示例,例如優(yōu)雅地關(guān)閉應(yīng)用服務(wù)、在命令行應(yīng)用中接收終止命令,需要的朋友可以參考下2023-02-02
Golang判斷struct/slice/map是否相等以及對(duì)比的方法總結(jié)
平時(shí)開(kāi)發(fā)中對(duì)比兩個(gè)struct或者map、slice是否相等是經(jīng)常遇到的,有很多對(duì)比的方式,比如==,reflect.DeepEqual(),cmp.Equal()等也是經(jīng)常容易混淆的,這么多種對(duì)比方式,適用場(chǎng)景和優(yōu)缺點(diǎn)都有哪些呢?今天我們來(lái)具體總結(jié)一下,感興趣的小伙伴們可以參考借鑒2022-11-11
go+redis實(shí)現(xiàn)消息隊(duì)列發(fā)布與訂閱的詳細(xì)過(guò)程
這篇文章主要介紹了go+redis實(shí)現(xiàn)消息隊(duì)列發(fā)布與訂閱,redis做消息隊(duì)列的缺點(diǎn):沒(méi)有持久化,一旦消息沒(méi)有人消費(fèi),積累到一定程度后就會(huì)丟失,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09
深入學(xué)習(xí)Golang并發(fā)編程必備利器之sync.Cond類型
Go?語(yǔ)言的?sync?包提供了一系列同步原語(yǔ),其中?sync.Cond?就是其中之一。本文將深入探討?sync.Cond?的實(shí)現(xiàn)原理和使用方法,幫助大家更好地理解和應(yīng)用?sync.Cond,需要的可以參考一下2023-05-05

