MVC基础用法

目录结构

主目录basic

  1. —— main.go

代码示例

main.go

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/kataras/iris"
  5. "github.com/kataras/iris/sessions"
  6. "github.com/kataras/iris/mvc"
  7. )
  8. func main() {
  9. app := iris.New()
  10. app.Logger().SetLevel("debug")
  11. mvc.Configure(app.Party("/basic"), basicMVC)
  12. app.Run(iris.Addr(":8080"))
  13. }
  14. func basicMVC(app *mvc.Application) {
  15. //当然,你可以在MVC应用程序中使用普通的中间件。
  16. app.Router.Use(func(ctx iris.Context) {
  17. ctx.Application().Logger().Infof("Path: %s", ctx.Path())
  18. ctx.Next()
  19. })
  20. //把依赖注入,controller(s)绑定
  21. //可以是一个接受iris.Context并返回单个值的函数(动态绑定)
  22. //或静态结构值(service)。
  23. app.Register(
  24. sessions.New(sessions.Config{}).Start,
  25. &prefixedLogger{prefix: "DEV"},
  26. )
  27. // GET: http://localhost:8080/basic
  28. // GET: http://localhost:8080/basic/custom
  29. app.Handle(new(basicController))
  30. //所有依赖项被绑定在父 *mvc.Application
  31. //被克隆到这个新子身上,父的也可以访问同一个会话。
  32. // GET: http://localhost:8080/basic/sub
  33. app.Party("/sub").Handle(new(basicSubController))
  34. }
  35. // If controller's fields (or even its functions) expecting an interface
  36. // but a struct value is binded then it will check
  37. // if that struct value implements
  38. // the interface and if true then it will add this to the
  39. // available bindings, as expected, before the server ran of course,
  40. // remember? Iris always uses the best possible way to reduce load
  41. // on serving web resources.
  42. //如果控制器结构体的字段(甚至其方法)需要接口
  43. //但结构值是绑定的,然后它会检查
  44. //如果该结构值实现
  45. //接口,如果为true,则将其添加到在服务器运行之前,正如预期的那样可用绑定,
  46. //记得吗? Iris总是使用最好的方法来减少负载关于提供网络资源。
  47. type LoggerService interface {
  48. Log(string)
  49. }
  50. type prefixedLogger struct {
  51. prefix string
  52. }
  53. func (s *prefixedLogger) Log(msg string) {
  54. fmt.Printf("%s: %s\n", s.prefix, msg)
  55. }
  56. type basicController struct {
  57. Logger LoggerService
  58. Session *sessions.Session
  59. }
  60. func (c *basicController) BeforeActivation(b mvc.BeforeActivation) {
  61. b.Handle("GET", "/custom", "Custom")
  62. }
  63. func (c *basicController) AfterActivation(a mvc.AfterActivation) {
  64. if a.Singleton() {
  65. panic("basicController should be stateless,a request-scoped,we have a 'Session' which depends on the context.")
  66. }
  67. }
  68. func (c *basicController) Get() string {
  69. count := c.Session.Increment("count", 1)
  70. body := fmt.Sprintf("Hello from basicController\nTotal visits from you: %d", count)
  71. c.Logger.Log(body)
  72. return body
  73. }
  74. func (c *basicController) Custom() string {
  75. return "custom"
  76. }
  77. type basicSubController struct {
  78. Session *sessions.Session
  79. }
  80. func (c *basicSubController) Get() string {
  81. count := c.Session.GetIntDefault("count", 1)
  82. return fmt.Sprintf("Hello from basicSubController.\nRead-only visits count: %d", count)
  83. }