前言
关于Iris安装IrisHostHTTP/2和安全任意iris.Runnerhost配置多个主机优雅的关闭带有TLS地自动公共域名app.Run的第二个参数使用配置自定义值从Context中访问配置Iris 进阶学习教程关于Iris
Iris
是一个通过GO编写的快速的,简单的,但是功能齐全和非常有效率的web框架Iris
为你下一个网站或者API提供一个精美的、使用简单的基础Iris
为使用者提供了一个完整且体面地支持
安装Iris
Iris
是一个跨平台的软件
//安装//go get /kataras/iris/v12@latestpackage mainimport "/kataras/iris/v12"func main() {app := iris.Default()app.Use(myMiddleware)app.Handle("GET", "/ping", func(context iris.Context) {context.JSON(iris.Map{"message": "pong"})})//监听端口app.Run(iris.Addr(":8080"))}//中间件func myMiddleware(ctx iris.Context) {ctx.Application().Logger().Infof("Runs before %s", ctx.Path())ctx.Next()}
如果想使用类似Gin的Air插件可以安装 rizla 工具
riazla main.go
代替go run main.go
Host
你可以开启服务监听任何
net.Listener
或者http.Server
类型的实例。初始化服务器的方法应该在最后传递给Run
函数。Go开发者最常用的方法是通过传递一个形如
hostname:ip
形式的网络地址来开启一个服务。Iris
中我们使用iris.Addr
,它是一个iris.Runner类型
app.Run(iris.Addr(":8080"))//有时候你在你的应用程序的其他地方创建一个标准库net/http服务器。并且你想使用它作为你的iris web程序提供服务app.Run(iris.Server(&http.Server{Addr:":8080"}))//最高级的用法是创建一个自定义的或者标准的`net/Listener`然后传递给app.Runl,err:=net.Listen("tcp4",":8080")if err!=nil{panic(err)}app.Run(iris.Listener(l))
HTTP/2和安全
如果你有文件密钥,你可以使用iris.TLS基于这些验证密钥开启https服务
app.Run(iris.TLS("127.0.0.1:443","mycert.cert","mykey.key"))//当你的应用准备部署生产的时候。可以使用iris.AutoTLS方法。它通过免费提供的证书开启一个安全服务app.Run(iris.AutoTLS(":443", "", "admin@"))
任意iris.Runner
有时你想要监听一些特定的东西,并且这些东西不是
net.Listener
类型的,你能够通过iris.Raw
方法做到
app.Run(iris.Raw(&http.Server{Addr:"8080"}.ListenAndServe)
host配置
形如上面的监听方式都可以在最后接受一个
func(*iris.Supervisor)
的可变参数。通过函数传递用来为特定的host添加配置其
app.run(iris.Addr(":8080"),func(h *iris.Supervisor){//当服务器关闭的时候触发回调函数h.RegisterOnShutdown(func(){printLn("server terminated")})})
你甚至可以在
app.Run
之前配置,但是不同的是,这个host配置器将会在所有的主机上执行
app:=iris.New()app.ConfigureHost(func(h *iris.Supervisor){h.RegisterOnShutdown(func(){println("server terminated")})})app.Run(iris.Addr(":8080"))//当run方法运行之后,通过Application#Hosts 字段提供的所有hosts你得应用服务都可以访问。但是最常用的场景可能出现在,运行app.Run之前访问hosts。有2种方法来获得访问hosts的监管。上面的一种是采用app.ConfigureHost方法来配置所有的程序的hosts。还有一种更加适合简单场景。用app.NewHost来创建一个新的host,然后用它的serve或者Listen函数。通过iris.Raw启动服务import net/httph:=app.NewHost(&http.Server{Addr:":8080"}h.RegisterOnShutdown(func(){println("server terminated")})app.Run(iris.Raw(h.ListenAndServe))
多个主机
你可以使用多个hosts来启动你的iris程序,
iris.Router
兼容net/http/Handler
函数,因此我们可以理解为,它可以被适用于任何net/http
服务器,然而,通过使用app.NewHost
是一个更加简单的方法,它也会复制所有的hosts配置器,并在app.Shutdwon时关闭所有依附在特定web服务的主机host,app:=iris.New();app.Get("/",indexHandler)
import ("/kataras/iris/v12""net/http")func main() {app := iris.Default()app.Handle("GET", "/ping", func(context iris.Context) {context.JSON(iris.Map{"message": "pong"})})//监听端口go app.Run(iris.Addr(":8080"))app.NewHost(&http.Server{Addr: ":9090"}).ListenAndServe()}curl 127.0.0.1:8080/pingcurl 127.0.0.1:9090/ping
优雅的关闭
为了手动地管理app被中断时需要做的事情,我们需要通过WithoutInterruptHandler选项禁用默认地行为,然后注册一个新的中断处理器
package mainimport ("context""time""/kataras/iris/v12")func main() {app := iris.New()// 注册新地中断器 程序终端地时候进行执行iris.RegisterOnInterrupt(func() {timeout := 5 * time.Secondctx, cancel := context.WithTimeout(context.Background(), timeout)defer cancel()// close all hostsapp.Shutdown(ctx)})app.Get("/", func(ctx iris.Context) {ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")})//禁用默认地中断器app.Run(iris.Addr(":8080"), iris.WithoutInterruptHandler)}
带有TLS地自动公共域名
Iris提供了
ngrok
的集成。ngrok
用于未开发者提供一个公共域名,便于你向你的同事展示工作进度等。1.下载ngrok,并且配置环境变量
2.简单传递withTunneling选项到app.Run中,示例如下
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.Configuration{Tunneling: iris.TunnelingConfiguration{AuthToken: "my-ngrok-auth-client-token",Bin:"/bin/path/for/ngrok",Region: "eu",WebInterface: "127.0.0.1:4040",Tunnels: []iris.Tunnel{{Name: "MyApp",Addr: ":8080",},},},}))
app.Run的第二个参数
前面章节的app.Run方法传入第一个参数,第二个参数是可选的、可变长的,接受一个或者多个
iris.Configurator
。一个iris.Configurator
是func(app *ris.Application)
类型的函数。自定义的iris.Configurator
能够改你的*iris.Application
。每个核心的配置字段都有一个内建的
iris.Configurator
。例如iris.WithoutStartupLog
,iris.WithCharset("UTF-8")
,iris.WithOptimizations
,iris.WithConfiguration(iris.Congiguration{...})
函数.每个模块、都有各自的配置项和选项。使用配置
唯一的配置结构体是
iris.Configuration
。所有的iris.Configuration
字段的默认值都是最常用的。iris
在app.Run运行之前不需要任何配置。但是你想要使用自定义的iris.Configurator
。你可以把你得配置器传给app.Configure
方法
package mainimport ("/kataras/iris/v12")func main() {application := iris.Default()//根绝配置项配置//configuration := iris.WithConfiguration(iris.Configuration{// Charset: "UTF-8",// DisableStartupLog: false,// EnableOptimizations: true,//})//从YAML加载//configuration := iris.WithConfiguration(iris.YAML("iris.yml"))//从TOML加载//configuration := iris.WithConfiguration(iris.TOML("./iris.tml"))//application.Run(iris.Addr(":8080"), configuration)//使用函数的方式传递application.Run(iris.Addr(":8080"), iris.WithoutInterruptHandler,iris.WithoutServerError(iris.ErrServerClosed),iris.WithoutBodyConsumptionOnUnmarshal,iris.WithoutAutoFireStatusCode,iris.WithOptimizations,iris.WithTimeFormat("Mon, 01 Jan 15:04:05 GMT"),)//当你想要改变一些iris.Configuration的字段的时候这是一个很好的做法。}
自定义值
iris.Configuration
包含一个名为Other map[string]interface
的字段,它可以接受任何自定义的key:value
选项,因此你可以依据需求使用这个字段来传递程序需要的指定的值。
app.Run(iris.Addr(":8080"),iris.WithOtherValue("ServerName","serverName"),iris.WithOtherValue("ServerOwner","admin@"),)
从Context中访问配置
在一个处理器中,通过下面的方式访问这些字段
ctx.Application().ConfigurationReadOnly()
Iris 进阶
Iris MVC支持
文档:
支持所有 HTTP 方法, 例如,如果想要写一个GET
那么在控制器中也要写一个Get()
函数,你可以在一个控制器内定义多个函数。
每个控制器通过BeforeActivation
自定义事件回调,用来自定义控制器的结构的方法与自定义路径处理程序,如下:(还未实验)
func (m \*MyController) BeforeActivation(b mvc.BeforeActivation) {// b.Dependencies().Add/Remove// b.Router().Use/UseGlobal/Done // and any standard API call you already know// 1-> Method// 2-> Path// 3-> The controller's function name to be parsed as handler// 4-> Any handlers that should run before the MyCustomHandlerb.Handle("GET", "/something/{id:long}", "MyCustomHandler", anyMiddleware...)}
通过控制器方法的输入参数访问动态路径参数,不需要绑定。当你使用 iris 的默认语法来解析控制器处理程序时,你需要在方法后加上 “.” 字符,大写字母是一个新的子路径。 官网例子:
1 mvc.New(app.Party("/user")).Handle(new(user.Controller))2 3 func(\*Controller) Get() - GET:/user.4 func(\*Controller) Post() - POST:/user.5 func(\*Controller) GetLogin() - GET:/user/login6 func(\*Controller) PostLogin() - POST:/user/login7 func(\*Controller) GetProfileFollowers() - GET:/user/profile/followers8 func(\*Controller) PostProfileFollowers() - POST:/user/profile/followers9 func(\*Controller) GetBy(id int64) - GET:/user/{param:long}10 func(\*Controller) PostBy(id int64) - POST:/user/{param:long}
mvc.New(app.Party("/profile")).Handle(new(profile.Controller))func(\*Controller) GetBy(username string) - GET:/profile/{param:string}mvc.New(app.Party("/assets")).Handle(new(file.Controller))func(\*Controller) GetByWildard(path string) - GET:/assets/{param:path}方法函数接收器支持的类型: int,int64, bool 和 string。
测试demo
main:
package mainimport ("admin/web/controllers""/kataras/golog""/kataras/iris""/kataras/iris/middleware/logger""/kataras/iris/mvc")func main() {app :\= newApp()//app.RegisterView(iris.HTML("./web", ".html")) //加载模版文件app.StaticWeb("/static", "web/resources/static") // 设置静态资源,暂时没有app.RegisterView(iris.HTML("web/views", ".html").Reload(true))golog.Info() //暂时不知道干啥的app.Run(iris.Addr(":8081"))}func router(this \*iris.Application){//main := this.Party("/", crs).AllowMethods(iris.MethodOptions) //中间件home:= this.Party("/")home.Get("/", func(ctx iris.Context) {// 首页模块ctx.View("index/index.html")})home.Get("/home", func(ctx iris.Context) {ctx.View("login/login.html")})home.Get("/welcome", func(ctx iris.Context) {ctx.View("welcome/welcome.html")})home.Get("/user/list/{page:int}",func(ctx iris.Context){ctx.View("user/list.html")})mvc.New(this.Party("/user")).Handle(new(controllers.UserController))}func newApp() \*iris.Application{app :\= iris.New()preSettring(app)router(app)return app}func preSettring(app \*iris.Application){// 定义错误显示级别app.Logger().SetLevel("debug")customLogger :\= logger.New(logger.Config{//状态显示状态代码Status: true,// IP显示请求的远程地址IP: true,//方法显示http方法Method: true,// Path显示请求路径Path: true,// Query将url查询附加到Path。Query: true,//Columns:true,// 如果不为空然后它的内容来自\`ctx.Values(),Get("logger\_message")//将添加到日志中。MessageContextKeys: \[\]string{"logger\_message"},//如果不为空然后它的内容来自\`ctx.GetHeader(“User-Agent”)MessageHeaderKeys: \[\]string{"User-Agent"},})app.Use(customLogger,//recover2.New(),)}
controller:
package controllersimport ("admin/models""admin/services""fmt")type UserController struct {Service services.UserService}// curl -i http://localhost:8080/movies// 如果您有敏感数据,这是正确的方法:// func (c \*MovieController) Get() (results \[\]viewmodels.Movie) {//data := c.Service.GetAll()//for \_, movie := range data {// results = append(results, viewmodels.Movie{movie})//}//return// }// Get方法// curl -i http://localhost:8080/user/listfunc (c \*UserController) Get() (result \[\]models.User) {fmt.Println("111111")////data := c.Service.GetAll()//for k,\_ := range data {// result = append(result,models.User{1,string(k)})//}return}// 获取用户列表// curl -i http://localhost:8080/user/listfunc (u \*UserController) GetList() (res string){fmt.Println("GetUserList")return "getUserlist"}
学习教程
iris+xorm教程
curl教程集之满汉全席
iris教程
go iris 实现GET、POST、PUT接口
Golang iris API文档生成器
iris实战学习