富贵资源网 Design By www.hznty.com

Iris介绍

编写一次并在任何地方以最小的机器功率运行,如Android、ios、Linux和Windows等。它支持Google Go,只需一个可执行的服务即可在所有平台。 Iris以简单而强大的api而闻名。 除了Iris为您提供的低级访问权限。 Iris同样擅长MVC。 它是唯一一个拥有MVC架构模式丰富支持的Go Web框架,性能成本接近于零。 Iris为您提供构建面向服务的应用程序的结构。 用Iris构建微服务很容易。

1. Iris框架

1.1 Golang框架

"text-align: center">详解Golang Iris框架的基本使用

1.2 安装Iris

Iris官网: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选项
# 使用完最好关闭,否则编译可能出错
go env -w GO111MODULE=on
# go get失败可以更改代理
go env -w GOPROXY=https://goproxy.cn,direct

2. 使用Iris构建服务端

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")
	// 设置recover从panics恢复,设置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"))
}

其他便捷设置方法:

// 默认设置日志和panic处理
app := iris.Default()

我们可以看到iris.Default()的源码:

// 注:默认设置"./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) {
		// 设置模板中"message"的参数值
		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使用文件记录

上述记录日志

// 获取当前时间
now := time.Now().Format("20060102") + ".log"
// 打开文件,如果不存在创建,如果存在追加文件尾,权限为:拥有者可读可写
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")
}
// 设置日志输出为文件
app.Logger().SetOutput(file)

到文件可以和中间件结合,以控制不必要的调试信息记录到文件

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的路由请求,如果想要打印其他状态码请求,需要另使用

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")
})

"htmlcode">

app.Get("/users/{id:uint64}", func(ctx iris.Context){
	id := ctx.Params().GetUint64Default("id", 0)
})

使用post传递参数

app.Post("/login", func(ctx iris.Context) {
		username := ctx.FormValue("username")
		password := ctx.FormValue("password")
		ctx.JSON(iris.Map{
			"Username": username,
			"Password": password,
		})
	})

以上就是Iris的基本入门使用,当然还有更多其他操作:中间件使用、正则表达式路由路径的使用、Cache、Cookie、Session、File Server、依赖注入、MVC等的用法,可以参照官方教程使用,后期有时间会写文章总结。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com