go web開發之iris(六)MVC基礎

這種模式類似於基於類(view)的結構。相比於前面函數式的編碼方式來書,邏輯性更強,結構也更加清晰。

配置方式1

package main

import (
   "fmt"
   "github.com/kataras/iris"
   "github.com/kataras/iris/mvc"
)

func main() {
   app := iris.New()

   // 配置
   mvc.Configure(app.Party("/root"),myMvc)

   app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
}

func myMvc(app *mvc.Application) {
   app.Handle(new(MyController))
}

// controller
type MyController struct {}

// 再添加路由
func (m *MyController) BeforeActivation(b mvc.BeforeActivation) {
   b.Handle("GET", "/something/{id:long}", "MyCustomHandler",hello)// method,path,funcName,middleware
}

func (m *MyController) Get() string {
   return "Hello World"
}

func (m *MyController) MyCustomHandler(id int64) string {
   return "MyCustomHandler"
}

func hello(ctx iris.Context) {
   fmt.Println("ctx")
   ctx.Next()
}

配置方式2

package main

import (
   "github.com/kataras/iris"
   "github.com/kataras/iris/middleware/logger"
   recover2 "github.com/kataras/iris/middleware/recover"
   "github.com/kataras/iris/mvc"
)

func main() {
   app := iris.New()

   app.Use(recover2.New()) // 恐慌恢復
   app.Use(logger.New()) // 輸入到終端

   mvc.New(app).Handle(new(Container))

   app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
}

type Container struct {}

func (c *Container) Get() mvc.Result {
   return mvc.Response{
      ContentType:"text/html",
      Text:"<h1>Welcome</h1>",
   }
}

func (c *Container) GetPing() string {
   return "ping"
}


func (c *Container) GetHello() interface{} {
   return map[string]string{
      "message":"Hello World",
   }
}

func (c *Container) BeforeActivation(b mvc.BeforeActivation) {
   b.Handle("GET","/hello/{name:string}","Hello")
}

func (c *Container) Hello(name string) string {
   return "Hello World " + name
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章