佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 詳解Golang Iris框架的基本使用

詳解Golang Iris框架的基本使用

熱門標(biāo)簽:AI電銷 網(wǎng)站排名優(yōu)化 服務(wù)外包 百度競價排名 地方門戶網(wǎng)站 鐵路電話系統(tǒng) 呼叫中心市場需求 Linux服務(wù)器

Iris介紹

編寫一次并在任何地方以最小的機器功率運行,如Android、ios、Linux和Windows等。它支持Google Go,只需一個可執(zhí)行的服務(wù)即可在所有平臺。 Iris以簡單而強大的api而聞名。 除了Iris為您提供的低級訪問權(quán)限。 Iris同樣擅長MVC。 它是唯一一個擁有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支持(實際上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.

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選項
# 使用完最好關(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("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è)置方法:

// 默認設(shè)置日志和panic處理
app := iris.Default()

我們可以看到iris.Default()的源碼:

// 注:默認設(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")
}

// 等價于下面
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有十分強大的路由處理程序,你能夠按照十分靈活的語法設(shè)置路由路徑,并且如果沒有涉及正則表達式,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 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)然還有更多其他操作:中間件使用、正則表達式路由路徑的使用、Cache、Cookie、Session、File Server、依賴注入、MVC等的用法,可以參照官方教程使用,后期有時間會寫文章總結(jié)。

到此這篇關(guān)于詳解Golang Iris框架的基本使用的文章就介紹到這了,更多相關(guān)Golang Iris框架使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • mac下安裝golang框架iris的方法
  • golang常用庫之操作數(shù)據(jù)庫的orm框架-gorm基本使用詳解
  • golang 網(wǎng)絡(luò)框架之gin的使用方法
  • golang日志框架之logrus的使用

標(biāo)簽:湖南 蘭州 衡水 黃山 湘潭 崇左 仙桃 銅川

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《詳解Golang Iris框架的基本使用》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    浦县| 图木舒克市| 汉川市| 永泰县| 六安市| 高尔夫| 南皮县| 沙雅县| 壤塘县| 泌阳县| 新巴尔虎右旗| 吉木乃县| 长垣县| 砀山县| 林口县| 建水县| 广元市| 辰溪县| 青龙| 潼南县| 肇东市| 孙吴县| 综艺| 鹤庆县| 项城市| 徐闻县| 大埔县| 微山县| 丹凤县| 米林县| 金秀| 秦皇岛市| 永泰县| 石渠县| 文昌市| 韶关市| 宜良县| 顺平县| 祥云县| 安西县| 巴彦淖尔市|