Iris 具有用于路由的表达语法,感觉就像在家一样。路由算法是强大的,通过 muxie 来处理请求和比其替代品(httprouter、gin、echo) 更快地匹配路由。

让我们没有任何麻烦地开始吧!

新建一个空文件,命名为 example.go,然后打开它复制粘贴下面的代码。

  1. package main
  2. import "github.com/kataras/iris/v12"
  3. func main() {
  4. app := iris.Default()
  5. app.Use(myMiddleware)
  6. app.Handle("GET", "/ping", func(ctx iris.Context) {
  7. ctx.JSON(iris.Map{"message": "pong"})
  8. })
  9. // Listens and serves incoming http requests
  10. // on http://localhost:8080.
  11. app.Run(iris.Addr(":8080"))
  12. }
  13. func myMiddleware(ctx iris.Context) {
  14. ctx.Application().Logger().Infof("Runs before %s", ctx.Path())
  15. ctx.Next()
  16. }

打开终端会话,执行下面的指令,然后再浏览器上访问 http://localhost:8000/ping

  1. $ go run example.go

展示更多(Show me more)

我们简单地启动和运行程序来获取一个页面。

  1. package main
  2. import "github.com/kataras/iris/v12"
  3. func main() {
  4. app := iris.New()
  5. // Load all templates from the "./views" folder
  6. // where extension is ".html" and parse them
  7. // using the standard `html/template` package.
  8. app.RegisterView(iris.HTML("./views", ".html"))
  9. // Method: GET
  10. // Resource: http://localhost:8080
  11. app.Get("/", func(ctx iris.Context) {
  12. // Bind: {{.message}} with "Hello world!"
  13. ctx.ViewData("message", "Hello world!")
  14. // Render template file: ./views/hello.html
  15. ctx.View("hello.html")
  16. })
  17. // Method: GET
  18. // Resource: http://localhost:8080/user/42
  19. //
  20. // Need to use a custom regexp instead?
  21. // Easy;
  22. // Just mark the parameter's type to 'string'
  23. // which accepts anything and make use of
  24. // its `regexp` macro function, i.e:
  25. // app.Get("/user/{id:string regexp(^[0-9]+$)}")
  26. app.Get("/user/{id:uint64}", func(ctx iris.Context) {
  27. userID, _ := ctx.Params().GetUint64("id")
  28. ctx.Writef("User ID: %d", userID)
  29. })
  30. // Start the server using a network address.
  31. app.Run(iris.Addr(":8080"))
  32. }

html 文件:./views/hello.html

  1. <html>
  2. <head>
  3. <title>Hello Page</title>
  4. </head>
  5. <body>
  6. <h1>{{ .message }}</h1>
  7. </body>
  8. </html>

想要当你的代码发生改变时自动重启你的程序?安装 rizla 工具,执行 rizla main.go 来替代 go run main.go