书接上回,咱们曾经装置好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模板来将数据实时渲染至页面中,欲知后事如何,且听下回分解。