Iris 具有用于路由的表达语法,感觉就像在家一样(译者:原文 which feels like home,大概意思是如同在家里一样舒服)。路由算法由 [muxie 项目](https://github.com/kataras/muxie) 提供支持,和 httprouter 和 gin 或 echo 等替代方案相比,该算法能够更快地处理请求和匹配路由。
让我们心无旁骛的开始。
创建一个空文件,假设其名称为 `example.go`,然后将其打开并复制粘贴以下代码到其中。
```
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.Default()
app.Use(myMiddleware)
app.Handle("GET", "/ping", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "pong"})
})
// 侦听并服务于传入的 http 请求
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
func myMiddleware(ctx iris.Context) {
ctx.Application().Logger().Infof("Runs before %s", ctx.Path())
ctx.Next()
}
```
启动终端 session 并执行以下操作。
```
# 运行 example.go 并且在浏览器上访问 http://localhost:8080/ping
$ go run example.go
```
# 展示更多!
让我们简要概述一下启动和运行的难易程度。
```
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
// 从 "./views" 文件夹加载所有
// 扩展名为 ".html" 的模版文件
// 并且使用 `html / template` 标准包解析它们。
app.RegisterView(iris.HTML("./views", ".html"))
// 方法: GET
// 资源: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// 绑定: {{.message}} 和 "Hello world!"
ctx.ViewData("message", "Hello world!")
// 渲染模板文件: ./views/hello.html
ctx.View("hello.html")
})
// 方法: GET
// 资源: http://localhost:8080/user/42
//
// 是否需要使用自定义正则表达式?
// 简单;
// 要接受任何内容,
// 只需将参数的类型标记为 'string' 并
// 利用其 `regexp` 宏函数, 即:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:uint64}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetUint64("id")
ctx.Writef("User ID: %d", userID)
})
// 使用网络地址启动服务器。
app.Run(iris.Addr(":8080"))
}
```
```
<!-- 文件: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
开发工具(原文:overview screen)
是否要在源代码更改发生时自动重新启动应用程序?
安装 [ rizla](https://github.com/kataras/rizla) 工具并执行 `rizla main.go`替代 `go run main.go`。
>译者:热加载工具很多,除了 `rizla`, 还有 [bee](https://github.com/beego/bee), [gowatch](https://gitee.com/silenceper/gowatch),[air](https://github.com/cosmtrek/air) 等等工具。
在下一节中,我们将详细了解 [路由](https://github.com/kataras/iris/wiki/Routing) 。