【Web 项目开发之Iris框架 | 青训营笔记】

330 阅读3分钟

image.png

这是我参与【第五届青训营】伴学笔记创作活动的第八天。 作为 go 中首屈一指的框架,Iris 具有许多优良特性,且应用广泛。此篇概述一下 Go Web 项目开发之 Iris 框架。

Web 项目开发之Iris框架

项目架构

CS模式

  1. 前台:客户端(client),面向用户的程序
  2. 后台:服务端(server),为前台应用提供数据和功能支撑

开发流程

  1. 需求确定
  2. 分析与设计
  3. 开发环境搭建(硬件环境 + 软件环境)
  4. 开发与测试(代码开发 + 测试)
  5. 文档编纂(记录相关文档,便于维护和对接)

Iris 框架

Iris 简介

速度最快的 Go 后端开发框架,具有以下特性:

  1. 聚焦高性能
  2. 健壮的静态路由支持和通配符子域名支持
  3. 支持定制的高可扩展性 Websocket ApI
  4. 方便的中间件和插件

等等。

Iris 框架安装

简单安装:go get -u github.com/kataras/iris(安装到 src 下的 github.com下)

编辑一个最简单的 Iris 的服务

  • 通过iris.New()方法可以实例化一个应用服务对象app
  • 通过Run方法开启端口监听服务,运行服务实例
package main
import "github.com/kataras/iris"
func main() {
    // 创建 app 结构体对象
    app := iris.New()
    // 执行+端口监听 (第二个参数可省略,用于未发现服务的错误)
    app.Run(iris.Addr("8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

Http 请求

Iris 框架的请求处理方式(Http 请求):app 中包含的方法 + 通用的 Handle 自定义编写

app直接调用方式

// 可用 Postman 测试
type Person {
    name string
    pwd string
}
func main() {
    app := iris.New()
    
    // 处理 Get 请求
    app.Get("/getrequest", func(context context.Context) {
        // 处理 http://localhost:8080/userpath 的 get 请求
        path := context.Path()  // 路径
        app.Logger().Info(path) // 打印日志,还有错误日志:app.Logger().Error()
        // 获取 get 请求所携带的参数
        userName := context.URLParam("username")
        // 返回 html 的 数据格式
        context.HTML("<h1>" + userName + "</h1>")
    })
    // 处理 Post 请求  (数据:Body: raw)
    app.Post("/postLogin", func(context context.Context) {
        path := context.Path() 
        app.Logger().Info(path)
        name := context.PostValue("name") // 获取参数
        pwd := context.PostValue("pwd")
        app.Logger().Info(name, " ", pwd)
        context.HTML("<h1>" + userName + "," + pwd + "</h1>")
        
        // 支持 json/xml 格式
        var person Person
        context.ReadJson(&person)  // 获取 json 格式数据并存储在 person 中
        // 同理有 readXML(&person)
        
        // 返回 json 格式数据
        context.Json(iris.Map{name:"wangming", "pwd":"hahahaha"})
    })
    
    app.Run(iris.Addr("8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

Handle 方式:app.Handle("GET", "/userinfo", func(){ } )

正则表达式 * 路由

// 根据传入的变量给网址起名
app.Get("/hello/{name}", func(context context.Context) {
    name := context.Params().Get("name") // 获取自定义的名字
})
// 可以给变量定义数据类型
app.Get("/hello/{name: string}", func(context context.Context) { ... })
​

Iris 设置操作

  1. 模块:如用户模块:

    • hello/user/register 注册
    • hello/user/login 登录
    • hello/user/info 获取用户信息
  2. 路由组请求:

    userParty := app.Party("/users", func(context context.Context){
        // 处理下一级请求
        context.Next()
    })
    // 可根据前面的调用后面的
    userParty.Get("/hello/{name}", func(context context.Context) {
        name := context.Params().Get("name") // 获取自定义的名字
    })
    ​
    // userParty.Done() :请求执行完成后调用,需手动显式的调用: Get里的context.Next()
    
  3. Iris 配置

    func main() {
        app := iris.New()
        
        // 法一:通过程序代码对应用进行全局配置
        app.Configure(iris.WithConfiguration(iris.Configuration{
            ...... // 具体略
        }))
        // 法二:tml 或 yaml 配置文件
        app.Configure(iris.WithConfiguration(iris.TOML("filepath/iris.tml")))
        // 法三:通过 json 配置文件进行应用配置
        file,_ := os.Open("filepath/config.json")
        defer file.Close()
        decoder := json.NewDecoder(file)
        conf := Coniguration{}
        err := decoder.Decode(&conf)
        if err != nil {
            fmt.Println("Error: ",err)
        }
        fmt.Println(conf.Port)
        
        app.Run(iris.Addr("8080"), iris.WithoutServerError(iris.ErrServerClosed))
    }
    ​
    type Coniguratio struct {
        ..... // 根据文件格式
    }