午夜无码人妻aⅴ大片色欲张津瑜,国产69久久久欧美黑人A片,色妺妺视频网,久久久久国产综合AV天堂

如何正確的使用Golang中的Iris框架-創(chuàng)新互聯(lián)

這篇文章給大家介紹如何正確的使用Golang中的Iris框架,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

創(chuàng)新互聯(lián)公司是一家專業(yè)提供臺前企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、成都網(wǎng)站建設(shè)、html5、小程序制作等業(yè)務(wù)。10年已為臺前眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)的建站公司優(yōu)惠進(jìn)行中。

1. Iris框架


1.1 Golang框架

??Golang常用框架有:Gin、Iris、Beego、Buffalo、Echo、Revel,其中Gin、Beego和Iris較為流行。Iris是目前流行Golang框架中提供MVC支持(實(shí)際上Iris使用MVC性能會略有下降)的框架,并且支持依賴注入,使用入門簡單,能夠快速構(gòu)建Web后端,也是目前幾個框架中發(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.

如何正確的使用Golang中的Iris框架

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是錯誤,如果版本大于11,可以使用下面打開GO111MODULE選項(xiàng)
# 使用完好關(guān)閉,否則編譯可能出錯
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("<h2>Hello Iris!</h2>")
		
	})
	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>
	<h2>{{ .message }}</h2>
</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")
}

// 等價于下面
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 使用文件記錄日志

 整個Application使用文件記錄

上述記錄日志

// 獲取當(dāng)前時間
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會計算其需求預(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 TypeGo TypeValidationRetrieve Helper
:stringstringanything (single path segment)Params().Get
:intint-9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host archParams().GetInt
:int8int8-128 to 127Params().GetInt8
:int16int16-32768 to 32767Params().GetInt16
:int32int32-2147483648 to 2147483647Params().GetInt32
:int64int64-9223372036854775808 to 92233720368?4775807Params().GetInt64
:uintuint0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host archParams().GetUint
:uint8uint80 to 255Params().GetUint8
:uint16uint160 to 65535Params().GetUint16
:uint32uint320 to 4294967295Params().GetUint32
:uint64uint640 to 18446744073709551615Params().GetUint64
:boolbool“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
:alphabeticalstringlowercase or uppercase lettersParams().Get
:filestringlowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenamesParams().Get
:pathstringanything, can be separated by slashes (path segments) but should be the last part of the route pathParams().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,
		})
	})

關(guān)于如何正確的使用Golang中的Iris框架就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

網(wǎng)頁標(biāo)題:如何正確的使用Golang中的Iris框架-創(chuàng)新互聯(lián)
當(dāng)前鏈接:http://www.ekvhdxd.cn/article34/doiise.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、移動網(wǎng)站建設(shè)、云服務(wù)器、網(wǎng)站導(dǎo)航微信小程序、關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司