【GO+Iris】Iris框架初识-《GO开发知识笔记》

admin 2025-11-04 01:10:34 编程 来源:ZONE.CI 全球网 0 阅读模式
  • HTTP/2和安全
  • 任意iris.Runner
  • host配置
  • 优雅的关闭
  • 带有TLS地自动公共域名
  • 自定义值
  • 从Context中访问配置
    1. Iris是一个通过GO编写的快速的,简单的,但是功能齐全和非常有效率的web框架
    2. Iris为你下一个网站或者API提供一个精美的、使用简单的基础
    3. Iris为使用者提供了一个完整且体面地支持

    安装IrisIris是一个跨平台的软件

    1. //安装
    2. //go get github.com/kataras/iris/v12@latest
    3. package main
    4. import "github.com/kataras/iris/v12"
    5. func main() {
    6. app := iris.Default()
    7. app.Use(myMiddleware)
    8. app.Handle("GET", "/ping", func(context iris.Context) {
    9. context.JSON(iris.Map{"message": "pong"})
    10. })
    11. //监听端口
    12. app.Run(iris.Addr(":8080"))
    13. }
    14. //中间件
    15. func myMiddleware(ctx iris.Context) {
    16. ctx.Application().Logger().Infof("Runs before %s", ctx.Path())
    17. ctx.Next()
    18. }

    如果想使用类似Gin的Air插件可以安装 rizla 工具 riazla main.go 代替 go run main.go

    Host你可以开启服务监听任何net.Listener或者http.Server类型的实例。初始化服务器的方法应该在最后传递给Run函数。

    Go开发者最常用的方法是通过传递一个形如hostname:ip形式的网络地址来开启一个服务。Iris中我们使用iris.Addr,它是一个iris.Runner类型

    1. app.Run(iris.Addr(":8080"))
    2. //有时候你在你的应用程序的其他地方创建一个标准库net/http服务器。并且你想使用它作为你的iris web程序提供服务
    3. app.Run(iris.Server(&http.Server{Addr:":8080"}))
    4. //最高级的用法是创建一个自定义的或者标准的`net/Listener`然后传递给app.Run
    5. l,err:=net.Listen("tcp4",":8080")
    6. if err!=nil{
    7. panic(err)
    8. }
    9. app.Run(iris.Listener(l))

    HTTP/2和安全

    如果你有文件密钥,你可以使用iris.TLS基于这些验证密钥开启https服务

    1. app.Run(iris.TLS("127.0.0.1:443","mycert.cert","mykey.key"))
    2. //当你的应用准备部署生产的时候。可以使用iris.AutoTLS方法。它通过https://letsencrypt.org免费提供的证书开启一个安全服务
    3. app.Run(iris.AutoTLS(":443", "example.com", "[email protected]"))

    任意iris.Runner

    有时你想要监听一些特定的东西,并且这些东西不是net.Listener类型的,你能够通过iris.Raw方法做到

    1. app.Run(iris.Raw(&http.Server{Addr:"8080"}.ListenAndServe)

    host配置

    形如上面的监听方式都可以在最后接受一个func(*iris.Supervisor)的可变参数。通过函数传递用来为特定的host添加配置其

    1. app.run(iris.Addr(":8080"),func(h *iris.Supervisor){
    2. //当服务器关闭的时候触发回调函数
    3. h.RegisterOnShutdown(func(){
    4. printLn("server terminated")
    5. })
    6. })

    你甚至可以在app.Run之前配置,但是不同的是,这个host配置器将会在所有的主机上执行

    1. app:=iris.New()
    2. app.ConfigureHost(func(h *iris.Supervisor){
    3. h.RegisterOnShutdown(func(){
    4. println("server terminated")
    5. })
    6. })
    7. app.Run(iris.Addr(":8080"))
    8. //当run方法运行之后,通过Application#Hosts 字段提供的所有hosts你得应用服务都可以访问。但是最常用的场景可能出现在,运行app.Run之前访问hosts。有2种方法来获得访问hosts的监管。
    9. 上面的一种是采用app.ConfigureHost方法来配置所有的程序的hosts。还有一种更加适合简单场景。用app.NewHost来创建一个新的host,然后用它的serve或者Listen函数。通过iris.Raw启动服务
    10. import net/http
    11. h:=app.NewHost(&http.Server{Addr:":8080"}
    12. h.RegisterOnShutdown(func(){
    13. println("server terminated")
    14. })
    15. 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)

    1. import (
    2. "github.com/kataras/iris/v12"
    3. "net/http"
    4. )
    5. func main() {
    6. app := iris.Default()
    7. app.Handle("GET", "/ping", func(context iris.Context) {
    8. context.JSON(iris.Map{"message": "pong"})
    9. })
    10. //监听端口
    11. go app.Run(iris.Addr(":8080"))
    12. app.NewHost(&http.Server{Addr: ":9090"}).ListenAndServe()
    13. }
    14. curl 127.0.0.1:8080/ping
    15. curl 127.0.0.1:9090/ping

    优雅的关闭

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

    1. package main
    2. import (
    3. "context"
    4. "time"
    5. "github.com/kataras/iris/v12"
    6. )
    7. func main() {
    8. app := iris.New()
    9. // 注册新地中断器 程序终端地时候进行执行
    10. iris.RegisterOnInterrupt(func() {
    11. timeout := 5 * time.Second
    12. ctx, cancel := context.WithTimeout(context.Background(), timeout)
    13. defer cancel()
    14. // close all hosts
    15. app.Shutdown(ctx)
    16. })
    17. app.Get("/", func(ctx iris.Context) {
    18. ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")
    19. })
    20. //禁用默认地中断器
    21. app.Run(iris.Addr(":8080"), iris.WithoutInterruptHandler)
    22. }

    带有TLS地自动公共域名

    Iris提供了ngrok的集成。ngrok用于未开发者提供一个公共域名,便于你向你的同事展示工作进度等。1.下载ngrok,并且配置环境变量2.简单传递withTunneling选项到app.Run中,示例如下

    1. app.Run(iris.Addr(":8080"), iris.WithConfiguration(
    2. iris.Configuration{
    3. Tunneling: iris.TunnelingConfiguration{
    4. AuthToken: "my-ngrok-auth-client-token",
    5. Bin: "/bin/path/for/ngrok",
    6. Region: "eu",
    7. WebInterface: "127.0.0.1:4040",
    8. Tunnels: []iris.Tunnel{
    9. {
    10. Name: "MyApp",
    11. Addr: ":8080",
    12. },
    13. },
    14. },
    15. }))

    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方法

    1. package main
    2. import (
    3. "github.com/kataras/iris/v12"
    4. )
    5. func main() {
    6. application := iris.Default()
    7. //根绝配置项配置
    8. //configuration := iris.WithConfiguration(iris.Configuration{
    9. // Charset: "UTF-8",
    10. // DisableStartupLog: false,
    11. // EnableOptimizations: true,
    12. //})
    13. //从YAML加载
    14. //configuration := iris.WithConfiguration(iris.YAML("iris.yml"))
    15. //从TOML加载
    16. //configuration := iris.WithConfiguration(iris.TOML("./iris.tml"))
    17. //application.Run(iris.Addr(":8080"), configuration)
    18. //使用函数的方式传递
    19. application.Run(iris.Addr(":8080"), iris.WithoutInterruptHandler,
    20. iris.WithoutServerError(iris.ErrServerClosed),
    21. iris.WithoutBodyConsumptionOnUnmarshal,
    22. iris.WithoutAutoFireStatusCode,
    23. iris.WithOptimizations,
    24. iris.WithTimeFormat("Mon, 01 Jan 2006 15:04:05 GMT"),
    25. )
    26. //当你想要改变一些iris.Configuration的字段的时候这是一个很好的做法。
    27. }

    自定义值

    iris.Configuration包含一个名为Other map[string]interface的字段,它可以接受任何自定义的key:value选项,因此你可以依据需求使用这个字段来传递程序需要的指定的值。

    1. app.Run(iris.Addr(":8080"),
    2. iris.WithOtherValue("ServerName","serverName"),
    3. iris.WithOtherValue("ServerOwner","[email protected]"),
    4. )

    从Context中访问配置

    在一个处理器中,通过下面的方式访问这些字段

    1. ctx.Application().ConfigurationReadOnly()

    Iris 进阶Iris MVC支持文档:支持所有 HTTP 方法, 例如,如果想要写一个 GET 那么在控制器中也要写一个 Get() 函数,你可以在一个控制器内定义多个函数。每个控制器通过 BeforeActivation 自定义事件回调,用来自定义控制器的结构的方法与自定义路径处理程序,如下:(还未实验)

    1. func (m \*MyController) BeforeActivation(b mvc.BeforeActivation) {
    2. // b.Dependencies().Add/Remove
    3. // b.Router().Use/UseGlobal/Done // and any standard API call you already know
    4. // 1-> Method
    5. // 2-> Path
    6. // 3-> The controller's function name to be parsed as handler
    7. // 4-> Any handlers that should run before the MyCustomHandler
    8. b.Handle("GET", "/something/{id:long}", "MyCustomHandler", anyMiddleware...)
    9. }

    通过控制器方法的输入参数访问动态路径参数,不需要绑定。当你使用 iris 的默认语法来解析控制器处理程序时,你需要在方法后加上 “.” 字符,大写字母是一个新的子路径。 官网例子:

    1. mvc.New(app.Party("/user")).Handle(new(user.Controller))
    2. func(\*Controller) Get() - GET:/user.
    3. func(\*Controller) Post() - POST:/user.
    4. func(\*Controller) GetLogin() - GET:/user/login
    5. func(\*Controller) PostLogin() - POST:/user/login
    6. func(\*Controller) GetProfileFollowers() - GET:/user/profile/followers
    7. func(\*Controller) PostProfileFollowers() - POST:/user/profile/followers
    8. func(\*Controller) GetBy(id int64) - GET:/user/{param:long}
    9. func(\*Controller) PostBy(id int64) - POST:/user/{param:long}
    1. mvc.New(app.Party("/profile")).Handle(new(profile.Controller))
    2. func(\*Controller) GetBy(username string) - GET:/profile/{param:string}
    3. mvc.New(app.Party("/assets")).Handle(new(file.Controller))
    4. func(\*Controller) GetByWildard(path string) - GET:/assets/{param:path}
    5. 方法函数接收器支持的类型: int,int64, bool 和 string。

    测试demomain:

    1. package main
    2. import (
    3. "admin/web/controllers"
    4. "github.com/kataras/golog"
    5. "github.com/kataras/iris"
    6. "github.com/kataras/iris/middleware/logger"
    7. "github.com/kataras/iris/mvc"
    8. )
    9. func main() {
    10. app :\= newApp()
    11. //app.RegisterView(iris.HTML("./web", ".html")) //加载模版文件
    12. app.StaticWeb("/static", "web/resources/static") // 设置静态资源,暂时没有
    13. app.RegisterView(iris.HTML("web/views", ".html").Reload(true))
    14. golog.Info() //暂时不知道干啥的
    15. app.Run(iris.Addr(":8081"))
    16. }
    17. func router(this \*iris.Application){
    18. //main := this.Party("/", crs).AllowMethods(iris.MethodOptions) //中间件
    19. home:= this.Party("/")
    20. home.Get("/", func(ctx iris.Context) { // 首页模块
    21. ctx.View("index/index.html")
    22. })
    23. home.Get("/home", func(ctx iris.Context) {
    24. ctx.View("login/login.html")
    25. })
    26. home.Get("/welcome", func(ctx iris.Context) {
    27. ctx.View("welcome/welcome.html")
    28. })
    29. home.Get("/user/list/{page:int}",func(ctx iris.Context){
    30. ctx.View("user/list.html")
    31. })
    32. mvc.New(this.Party("/user")).Handle(new(controllers.UserController))
    33. }
    34. func newApp() \*iris.Application{
    35. app :\= iris.New()
    36. preSettring(app)
    37. router(app)
    38. return app
    39. }
    40. func preSettring(app \*iris.Application){
    41. // 定义错误显示级别
    42. app.Logger().SetLevel("debug")
    43. customLogger :\= logger.New(logger.Config{
    44. //状态显示状态代码
    45. Status: true,
    46. // IP显示请求的远程地址
    47. IP: true,
    48. //方法显示http方法
    49. Method: true,
    50. // Path显示请求路径
    51. Path: true,
    52. // Query将url查询附加到Path。
    53. Query: true,
    54. //Columns:true,
    55. // 如果不为空然后它的内容来自\`ctx.Values(),Get("logger\_message")
    56. //将添加到日志中。
    57. MessageContextKeys: \[\]string{"logger\_message"},
    58. //如果不为空然后它的内容来自\`ctx.GetHeader(“User-Agent”)
    59. MessageHeaderKeys: \[\]string{"User-Agent"},
    60. })
    61. app.Use(
    62. customLogger,
    63. //recover2.New(),
    64. )
    65. }

    controller:

    1. package controllers
    2. import (
    3. "admin/models"
    4. "admin/services"
    5. "fmt"
    6. )
    7. type UserController struct {
    8. Service services.UserService
    9. }
    10. // curl -i http://localhost:8080/movies
    11. // 如果您有敏感数据,这是正确的方法:
    12. // func (c \*MovieController) Get() (results \[\]viewmodels.Movie) {
    13. // data := c.Service.GetAll()
    14. // for \_, movie := range data {
    15. // results = append(results, viewmodels.Movie{movie})
    16. // }
    17. // return
    18. // }
    19. // Get方法
    20. // curl -i http://localhost:8080/user/list
    21. func (c \*UserController) Get() (result \[\]models.User) {
    22. fmt.Println("111111")
    23. //
    24. //data := c.Service.GetAll()
    25. //for k,\_ := range data {
    26. // result = append(result,models.User{1,string(k)})
    27. //}
    28. return
    29. }
    30. // 获取用户列表
    31. // curl -i http://localhost:8080/user/list
    32. func (u \*UserController) GetList() (res string){
    33. fmt.Println("GetUserList")
    34. return "getUserlist"
    35. }
    以太坊cppgolang区别 编程

    以太坊cppgolang区别

    以太坊是一种去中心化的开源平台,它采用智能合约技术,旨在构建和运行不受干扰的分布式应用程序。作为目前最受欢迎的区块链平台之一,以太坊提供了多种编程语言的支持,其
    progolang 编程

    progolang

    Go语言(Golang)是由Google开发的一门静态类型编程语言。作为一名专业的Golang开发者,我深知这门语言的优势和特点。在本文中,我将介绍Golang
    golangn个发送者 编程

    golangn个发送者

    Golang是一种开源的编程语言,由Google团队开发,旨在提高程序的并发性和简化软件开发过程。在Go语言中,有时需要向多个接收者发送信息。本文将介绍如何在G
    golang技能图谱 编程

    golang技能图谱

    从互联网行业的快速发展到人工智能技术的日益成熟,各种编程语言也应运而生。而在这众多的编程语言中,Golang(即Go)作为一门强大且高效的开发语言备受关注。Go
    评论:0   参与:  8