overview示例

目录结构

主目录overview

  1. —— views
  2. —— user
  3. —— create_verification.html
  4. —— profile.html
  5. —— main.go

示例代码

main.go

  1. package main
  2. import (
  3. "github.com/kataras/iris"
  4. )
  5. //User结构体用户绑定提交参数,与json返回
  6. type User struct {
  7. Username string `json:"username"`
  8. Firstname string `json:"firstname"`
  9. Lastname string `json:"lastname"`
  10. City string `json:"city"`
  11. Age int `json:"age"`
  12. }
  13. func main() {
  14. app := iris.New()
  15. // app.Logger().SetLevel("disable")禁用错误日志记录
  16. //使用std html/template引擎定义模板
  17. //使用“.html”文件扩展名解析并加载“./views”文件夹中的所有文件。
  18. //在每个请求上重新加载模板(开发模式)。
  19. app.RegisterView(iris.HTML("./views", ".html").Reload(true))
  20. //为特定的http错误注册自定义处理程序。
  21. app.OnErrorCode(iris.StatusInternalServerError, func(ctx iris.Context) {
  22. // .Values用于在处理程序,中间件之间进行通信。
  23. errMessage := ctx.Values().GetString("error")
  24. if errMessage != "" {
  25. ctx.Writef("Internal server error: %s", errMessage)
  26. return
  27. }
  28. ctx.Writef("(Unexpected) internal server error")
  29. })
  30. app.Use(func(ctx iris.Context) {
  31. ctx.Application().Logger().Infof("Begin request for path: %s", ctx.Path())
  32. ctx.Next()
  33. })
  34. // app.Done(func(ctx iris.Context) {]})
  35. // POST: scheme://mysubdomain.$domain.com/decode
  36. app.Subdomain("mysubdomain.").Post("/decode", func(ctx iris.Context) {})
  37. // 请求方法 POST: http://localhost:8080/decode
  38. app.Post("/decode", func(ctx iris.Context) {
  39. var user User
  40. ctx.ReadJSON(&user)
  41. ctx.Writef("%s %s is %d years old and comes from %s", user.Firstname, user.Lastname, user.Age, user.City)
  42. })
  43. // 请求方法 GET: http://localhost:8080/encode
  44. app.Get("/encode", func(ctx iris.Context) {
  45. doe := User{
  46. Username: "Johndoe",
  47. Firstname: "John",
  48. Lastname: "Doe",
  49. City: "Neither FBI knows!!!",
  50. Age: 25,
  51. }
  52. ctx.JSON(doe)
  53. })
  54. // 请求方法 GET: http://localhost:8080/profile/anytypeofstring
  55. app.Get("/profile/{username:string}", profileByUsername)
  56. usersRoutes := app.Party("/users", logThisMiddleware)
  57. {
  58. // 请求方法 GET: http://localhost:8080/users/42
  59. usersRoutes.Get("/{id:int min(1)}", getUserByID)
  60. // 请求方法 POST: http://localhost:8080/users/create
  61. usersRoutes.Post("/create", createUser)
  62. }
  63. //在localhost端口8080上监听传入的HTTP/1.x和HTTP/2客户端
  64. app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8"))
  65. }
  66. func logThisMiddleware(ctx iris.Context) {
  67. ctx.Application().Logger().Infof("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr())
  68. //.Next继续运行下一个链上的处理程序(中间件)
  69. //如果没有,程序就会在这里停止了,不会向下面继续执行
  70. ctx.Next()
  71. }
  72. func profileByUsername(ctx iris.Context) {
  73. // .Params用于获取动态路径参数
  74. username := ctx.Params().Get("username")
  75. ctx.ViewData("Username", username)
  76. //渲染“./views/user/profile.html”
  77. //使用 {{ .Username }}将动态路径参数,渲染到html页面
  78. ctx.View("user/profile.html")
  79. }
  80. func getUserByID(ctx iris.Context) {
  81. userID := ctx.Params().Get("id") //或直接转换为:.Values().GetInt/GetInt64等...
  82. user := User{Username: "username" + userID}
  83. ctx.XML(user)
  84. }
  85. func createUser(ctx iris.Context) {
  86. var user User
  87. err := ctx.ReadForm(&user)
  88. if err != nil {
  89. ctx.Values().Set("error", "creating user, read and parse form failed. "+err.Error())
  90. ctx.StatusCode(iris.StatusInternalServerError)
  91. return
  92. }
  93. //渲染“./views/user/create_verification.html”
  94. //{{ . }}相当于User结构体,例如{{ .Username }}表示User结构体的Username字段等等...
  95. ctx.ViewData("", user)
  96. ctx.View("user/create_verification.html")
  97. }

/views/user/create_verification.html

  1. <html>
  2. <head><title>Create verification</title></head>
  3. <body>
  4. <h1> Create Verification </h1>
  5. <table style="width:550px">
  6. <tr>
  7. <th>Username</th>
  8. <th>Firstname</th>
  9. <th>Lastname</th>
  10. <th>City</th>
  11. <th>Age</th>
  12. </tr>
  13. <tr>
  14. <td>{{ .Username }}</td>
  15. <td>{{ .Firstname }}</td>
  16. <td>{{ .Lastname }}</td>
  17. <td>{{ .City }}</td>
  18. <td>{{ .Age }}</td>
  19. </tr>
  20. </table>
  21. </body>
  22. </html>

/views/user/profile.html

  1. <html>
  2. <head><title>Profile page</title></head>
  3. <body>
  4. <h1> Profile </h1>
  5. <b> {{ .Username }} </b>
  6. </body>
  7. </html>