彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-项目入口与路由EP01

by Liu Yue/2022-08-16

    书接上回,我们已经安装好Iris框架,并且构建好了Iris项目,同时配置了fresh自动监控项目的实时编译,万事俱备,只欠东风,彩虹女神蓄势待发。现在我们来看看Iris的基础功能,如何编写项目入口文件以及配置路由系统。

    项目入口

    事实上,Iris遵循的是单一入口模式,说白了就是单一入口文件main.go处理项目所有的来源请求,如此,项目就避免了因为多个文件处理不同的请求而增加的安全性风险,同时也更便于项目的统筹管理。在上一篇文章:急如闪电快如风,彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-初始化项目EP00 中,我们已经编写好了入口文件main.go:

package main

import "github.com/kataras/iris/v12"

func main() {
app := iris.New()
app.Use(iris.Compression)

app.Get("/", func(ctx iris.Context) {
ctx.HTML("你好 <strong>%s</strong>!", "女神")
})

app.Listen(":5000")
}

    这里解释一下各行代码含义,首先声明包名:

package main

    随后导入Iris包,注意这里的版本是最新的v12:

import "github.com/kataras/iris/v12"

    接着声明入口(main)函数,并且初始化Iris结构体:

app := iris.New()

    随后加载iris.Compression模块:

app.Use(iris.Compression)

    这里Compression是Iris内部对IO数据进行压缩的模块,可以提高数据传输速度。

    接着编写路由注册,并使用ctx结构体变量来打印数据:

app.Get("/", func(ctx iris.Context) {
ctx.HTML("你好 <strong>%s</strong>!", "女神")
})

    最后监听系统的5000端口:

app.Listen(":5000")

    在此基础上,进行进一步的改造:

type Article struct {
Title string `json:"标题"`
}

    这里我们声明一个叫做Artile(文章)的结构体,该结构体可以理解为博客系统中文章的对象类,结构体内有一个数据类型为字符串的字段(属性)Title(标题),其隐射到Json结果的描述为“标题”。

    接着声明函数:

func list(ctx iris.Context) {
article := []Article{
{"iris第一章"},
{"iris第二章"},
{"iris第三章"},
}

ctx.JSON(article)

}

    这里我们声明一个叫做list的函数,参数为ctx结构体,作用是将文章的标题列表(切片),通过Json的形式返回。

    最后将全局注册的路由,改造为子路由注册:

articleAPI := app.Party("/")
{
articleAPI.Use(iris.Compression)
articleAPI.Get("/", list)

}

    这里使用Iris结构体变量内置的Party方法。

    完成入口文件代码:

package main

import "github.com/kataras/iris/v12"

func main() {
app := iris.New()

articleAPI := app.Party("/")
{
articleAPI.Use(iris.Compression)
articleAPI.Get("/", list)

}

app.Listen(":5000")
}

type Article struct {
Title string `json:"标题"`
}

func list(ctx iris.Context) {
article := []Article{
{"iris第一章"},
{"iris第二章"},
{"iris第三章"},
}

ctx.JSON(article)

}

    修改完毕后,fresh服务会自动帮我们重新编译项目,然后访问http://localhost:5000

    浏览器显示:

[
{
标题: "iris第一章"
},
{
标题: "iris第二章"
},
{
标题: "iris第三章"
}
]

    如此,通过入口文件返回子路由结构体数据的例子就完成了。

    路由与请求方式

    除了GET请求方式,Iris也支持其他的一些请求方式,一共八种:

app.Get("/someGet", getting)
app.Post("/somePost", posting)
app.Put("/somePut", putting)
app.Delete("/someDelete", deleting)
app.Patch("/somePatch", patching)
app.Header("/someHead", head)
app.Options("/someOptions", options)

    这里只需要将对应的函数进行绑定即可,比如:

func testpost(ctx iris.Context) {

ctx.WriteString("post请求测试")

}

    随后绑定Post请求:

articleAPI.Post("/", testpost)

    接着编写请求脚本,在项目以外的目录下建立tests.go文件:

package main

import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)

func main() {

resp, err := http.Post("http://localhost:5000", "application/json;charset=utf-8", strings.NewReader("name=test"))
if err != nil {
fmt.Println(err)
return
}

body, err := ioutil.ReadAll(resp.Body)

fmt.Println(string(body))

}

    这里通过http包的Post方法来请求http://localhost:5000

    系统返回:

post请求测试

    没有问题。

    路由传参

    在Iris的路由体系中,我们可以直接通过网址进行参数的传递:

app.Get("/user/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
ctx.Writef("Hello %s", name)
})

    随后编写请求脚本:

package main

import (
"fmt"
"io/ioutil"
"net/http"
)

func main() {

resp, err := http.Get("http://localhost:5000/user/123")
if err != nil {
fmt.Println(err)
return
}

body, err := ioutil.ReadAll(resp.Body)

fmt.Println(string(body))

}

    程序返回:

Hello 123

    需要注意的是,这种传参方式并不会匹配单独的/user路径,所以参数不能为空才能匹配到。

    如果参数为空,也需要向下匹配,可以采用这种方式:

app.Get("/user/{name}/{action:path}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
action := ctx.Params().Get("action")
message := name + " is " + action
ctx.WriteString(message)
})

    同时也可以声明参数类型:

app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
ctx.GetCurrentRoute().Tmpl().Src == "/user/{name:string}/{action:path}" // true
})

    Iris内置支持的参数类型:

Param Type Go Type Validation Retrieve Helper
:string string anything (single path segment) Params().Get
:uuid string uuidv4 or v1 (single path segment) Params().Get
:int int -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch Params().GetInt
:int8 int8 -128 to 127 Params().GetInt8
:int16 int16 -32768 to 32767 Params().GetInt16
:int32 int32 -2147483648 to 2147483647 Params().GetInt32
:int64 int64 -9223372036854775808 to 9223372036854775807 Params().GetInt64
:uint uint 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host arch Params().GetUint
:uint8 uint8 0 to 255 Params().GetUint8
:uint16 uint16 0 to 65535 Params().GetUint16
:uint32 uint32 0 to 4294967295 Params().GetUint32
:uint64 uint64 0 to 18446744073709551615 Params().GetUint64
:bool bool "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" Params().GetBool
:alphabetical string lowercase or uppercase letters Params().Get
:file string lowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenames Params().Get
:path string anything, can be separated by slashes (path segments) but should be the last part of the route path Params().Get

    除此以外,Iris也支持传统的传参方式:

func main() {
app := iris.Default()

// Query string parameters are parsed using the existing underlying request object.
// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
app.Get("/welcome", func(ctx iris.Context) {
firstname := ctx.URLParamDefault("firstname", "Guest")
lastname := ctx.URLParam("lastname") // shortcut for ctx.Request().URL.Query().Get("lastname")

ctx.Writef("Hello %s %s", firstname, lastname)
})
app.Listen(":8080")
}

    这里注意,如果参数为空,可以通过ctx结构体绑定URLParamDefault方法来设置默认值。

    结语

    通过Iris内置的路由、模型结构体、以及对应的结构体绑定方法,我们已经可以实现普通请求的响应,同时通过多种方式获取到请求的参数,下一步,将会结合Iris模板来将数据实时渲染至页面中,欲知后事如何,且听下回分解。