详解Golang Iris框架的基本使用

 更新时间:2020年11月27日 11:29:44   作者:WillAlso  
这篇文章主要介绍了Golang Iris框架的基本使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

Iris介绍

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

1. Iris框架

1.1 Golang框架

  Golang常用框架有:Gin、Iris、Beego、Buffalo、Echo、Revel,其中Gin、Beego和Iris较为流行。Iris是目前流行Golang框架中唯一提供MVC支持(实际上Iris使用MVC性能会略有下降)的框架,并且支持依赖注入,使用入门简单,能够快速构建Web后端,也是目前几个框架中发展最快的,从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.

star chart

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

  Iris有十分强大的路由处理程序,你能够按照十分灵活的语法设置路由路径,并且如果没有涉及正则表达式,Iris会计算其需求预先编译索引,用十分小的性能消耗来完成路由处理。

注:ctx.Params()和ctx.Values()是不同的,下面是官网给出的解释:

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可以使用的参数类型

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

在路径中使用参数

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等的用法,可以参照官方教程使用,后期有时间会写文章总结。

到此这篇关于详解Golang Iris框架的基本使用的文章就介绍到这了,更多相关Golang Iris框架使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • golang字符串切片去重的几种算法

    golang字符串切片去重的几种算法

    这篇文章主要介绍了golang字符串切片去重的几种算法的相关资料,需要的朋友可以参考下
    2023-09-09
  • go语言K8S 的 informer机制浅析

    go语言K8S 的 informer机制浅析

    这篇文章为大家主要介绍了go语言K8S 的 informer机制浅析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • golang判断字符串是是否包含另一字符串的示例代码

    golang判断字符串是是否包含另一字符串的示例代码

    在Go语言中,可以使用strings.Contains()函数来判断一个字符串是否包含另一个字符串,该函数接受两个参数:要搜索的字符串和要查找的子字符串,如果子字符串存在于要搜索的字符串中,则返回true,否则返回false,下面通过示例详细介绍,感兴趣的朋友一起看看吧
    2023-09-09
  • GoLang基础学习之go test测试

    GoLang基础学习之go test测试

    相信每位编程开发者们应该都知道,Golang作为一门标榜工程化的语言,提供了非常简便、实用的编写单元测试的能力,下面这篇文章主要给大家介绍了关于GoLang基础学习之go test测试的相关资料,需要的朋友可以参考下
    2022-08-08
  • Go语言中的Base64编码原理介绍以及使用

    Go语言中的Base64编码原理介绍以及使用

    Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,可用于在HTTP环境下传递较长的标识信息,下面这篇文章主要给大家介绍了关于Go语言中的Base64编码原理介绍以及使用的相关资料,需要的朋友可以参考下
    2022-01-01
  • 拦截信号Golang应用优雅关闭的操作方法

    拦截信号Golang应用优雅关闭的操作方法

    这篇文章主要介绍了拦截信号优雅关闭Golang应用,本文介绍了信号的概念及常用信号,并给出了应用广泛的几个示例,例如优雅地关闭应用服务、在命令行应用中接收终止命令,需要的朋友可以参考下
    2023-02-02
  • Go语言库系列之flag的具体使用

    Go语言库系列之flag的具体使用

    这篇文章主要介绍了Go语言库系列之flag的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Golang判断struct/slice/map是否相等以及对比的方法总结

    Golang判断struct/slice/map是否相等以及对比的方法总结

    平时开发中对比两个struct或者map、slice是否相等是经常遇到的,有很多对比的方式,比如==,reflect.DeepEqual(),cmp.Equal()等也是经常容易混淆的,这么多种对比方式,适用场景和优缺点都有哪些呢?今天我们来具体总结一下,感兴趣的小伙伴们可以参考借鉴
    2022-11-11
  • go+redis实现消息队列发布与订阅的详细过程

    go+redis实现消息队列发布与订阅的详细过程

    这篇文章主要介绍了go+redis实现消息队列发布与订阅,redis做消息队列的缺点:没有持久化,一旦消息没有人消费,积累到一定程度后就会丢失,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-09-09
  • 深入学习Golang并发编程必备利器之sync.Cond类型

    深入学习Golang并发编程必备利器之sync.Cond类型

    Go 语言的 sync 包提供了一系列同步原语,其中 sync.Cond 就是其中之一。本文将深入探讨 sync.Cond 的实现原理和使用方法,帮助大家更好地理解和应用 sync.Cond,需要的可以参考一下
    2023-05-05

最新评论