【GO+Iris】Iris框架初识_码农印象的博客-CSDN博客_go iris - 大写字母是一个新的子路径

前言

在这里插入图片描述

关于Iris

  1. Iris是一个通过GO编写的快速的,简单的,但是功能齐全和非常有效率的web框架
  2. Iris为你下一个网站或者API提供一个精美的、使用简单的基础
  3. Iris为使用者提供了一个完整且体面地支持

安装Iris

Iris是一个跨平台的软件
//安装
//go get github.com/kataras/iris/v12@latest
package main
import "github.com/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.Run
l,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方法。它通过https://letsencrypt.org免费提供的证书开启一个安全服务
app.Run(iris.AutoTLS(":443", "example.com", "admin@example.com"))

任意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/http
h:=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 (
  "github.com/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/ping
curl 127.0.0.1:9090/ping

优雅的关闭

为了手动地管理app被中断时需要做的事情,我们需要通过WithoutInterruptHandler选项禁用默认地行为,然后注册一个新的中断处理器

package main

import (
  "context"
  "time"

  "github.com/kataras/iris/v12"
)
func main() {
  app := iris.New()
  // 注册新地中断器 程序终端地时候进行执行
  iris.RegisterOnInterrupt(func() {
      timeout := 5 * time.Second
      ctx, cancel := context.WithTimeout(context.Background(), timeout)
      defer cancel()
      // close all hosts
      app.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.Configuratorfunc(app *ris.Application)类型的函数。自定义的iris.Configurator能够改你的*iris.Application

每个核心的配置字段都有一个内建的iris.Configurator。例如iris.WithoutStartupLog,iris.WithCharset("UTF-8"),iris.WithOptimizationsiris.WithConfiguration(iris.Congiguration{...}) 函数.每个模块、都有各自的配置项和选项。

使用配置

唯一的配置结构体是iris.Configuration。所有的iris.Configuration字段的默认值都是最常用的。iris在app.Run运行之前不需要任何配置。但是你想要使用自定义的iris.Configurator。你可以把你得配置器传给app.Configure方法

package main

import (
  "github.com/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 2006 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@example.com"),
)

从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 MyCustomHandler
    b.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/login
 6 func(\*Controller) PostLogin() - POST:/user/login
 7 func(\*Controller) GetProfileFollowers() - GET:/user/profile/followers
 8 func(\*Controller) PostProfileFollowers() - POST:/user/profile/followers
 9 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 main

import (
    "admin/web/controllers"
    "github.com/kataras/golog"
    "github.com/kataras/iris"
    "github.com/kataras/iris/middleware/logger"
    "github.com/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 controllers

import (
    "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/list
func (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/list
func (u \*UserController) GetList() (res string){
    fmt.Println("GetUserList")
    return "getUserlist"
}

学习教程

iris+xorm教程
curl教程集之满汉全席
iris教程
go iris 实现GET、POST、PUT接口
Golang iris API文档生成器
iris实战学习


原网址: 访问
创建于: 2022-10-02 22:50:16
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论