美文网首页
go web开发之iris(六)MVC基础

go web开发之iris(六)MVC基础

作者: 东京的雨不会淋湿首尔 | 来源:发表于2019-07-18 09:24 被阅读0次

    这种模式类似于基于类(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
    }
    
    

    相关文章

      网友评论

          本文标题:go web开发之iris(六)MVC基础

          本文链接:https://www.haomeiwen.com/subject/wskklctx.html