如何使用Iris框架建立web服务
解决问题:使用iris框架建立web服务
前言
在网上能找到的关于iris框架的资料都比较少,对初学者很不友好,我也是看了一些比较官方的文档才入门的。在这里放两个学习链接,仅供参考!
Go iris中文文档
Go web iris从入门到入土
Iris框架特性
- 专注于高性能
- 简单流畅的API
- 高扩展性
- 强大的路由和中间件生态系统
- 上下文
- 身份验证
- 视图系统.支持五种模板隐隐 完全兼容 html/template
安装iris框架
go get github.com/kataras/iris
安装完框架之后,创建go文件,开始编写代码…
创建app
//使用127.0.0.1:9999,编码格式为UTF-8
app := iris.New()
app.Run(iris.Addr(":9999"), iris.WithCharset("UTF-8"))
配置app
可以使用多种方法来配置app
- 使用自带函数
函数原型
func (app *Application) Configure(configurators ...Configurator) *Application {}
app.Configure(iris.WithConfiguration(iris.Configuration{ DisableStartupLog:false}))
//也可以使用app.Run()的第二个参数
app.Run(iris.Addr(":9999"), iris.WithConfiguration(iris.Configuration{
DisableStartupLog:false}))
- 使用TOML配置文件
在当前目录下创建一个名为config.tml的文件并写入配置内容:
DisablePathCorrection = false
EnablePathEscape = false
FireMethodNotAllowed = true
DisableBodyConsumptionOnUnmarshal = false
TimeFormat = "Mon, 01 Jan 2006 15:04:05 GMT"
Charset = "UTF-8"
[Other]
MyServerName = "iris"
在程序中读取tml文件配置
app.Run(iris.Addr(":9999"), iris.WithConfiguration(iris.TOML("config.tml")))
-
使用YAML配置文件
和TOML的使用方法大致相同,创建config.yml
在程序中读取tml文件配置
app.Run(iris.Addr(":9999"), iris.WithConfiguration(iris.YAML("config.yml")))
-
使用JSON配置文件
大致内容也与上面的大致一致,这里就不详细写了,有需要自行百度
关于错误代码
404 下面的这段代码实现了对404的错误定义
//第一个参数404的常量,第二个是错误处理函数
app.OnErrorCode(iris.StatusNotFound,err.NotFound)
iris中还有这些错误定义
StatusBadRequest = 400 // RFC 7231, 6.5.1
StatusUnauthorized = 401 // RFC 7235, 3.1
StatusPaymentRequired = 402 // RFC 7231, 6.5.2
StatusForbidden = 403 // RFC 7231, 6.5.3
StatusInternalServerError = 500 // RFC 7231, 6.6.1
StatusNotImplemented = 501 // RFC 7231, 6.6.2
StatusBadGateway = 502 // RFC 7231, 6.6.3
StatusServiceUnavailable = 503 // RFC 7231, 6.6.4
StatusGatewayTimeout = 504 // RFC 7231, 6.6.5
StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6
源代码(使用函数封装一下)
package main
import (
"github.com/kataras/iris"
)
func main() {
//创建新app并设置首页
app := newApp()
//配置
configation(app)
// 启动服务器
app.Run(iris.Addr(":9999"), iris.WithCharset("UTF-8"), iris.WithoutServerError(iris.ErrServerClosed))
// 监听地址:本服务器上任意id端口9999,设置字符集utf8
}
//创建App
func newApp() *iris.Application {
app := iris.New() // 实例一个iris对象
return app
}
//配置App信息
func configation(app *iris.Application){
//这里可以改为使用JSON文件配置信息
app.Configure(iris.WithConfiguration(iris.Configuration{
Charset: "UTF-8",
}))
//错误配置 匹配错误页面 后期添加自动匹配
app.OnErrorCode(iris.StatusNotFound,err.NotFound)
app.OnErrorCode(iris.StatusInternalServerError,err.InternalServerError)
}
运行结果
当显示下图的时候就可以访问网页了
总结
今天写了iris框架的建立web服务,相对于python的django要简洁的多,速度也快上了不少,下一篇写get,post这一类的基本操作
2020.6.19