irisMVC包的使用

「这是我参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战」。

mvc

::: tip mvc包简介

  • Iris框架中,封装了mvc包作为对mvc架构的支持,方便开发者遵循mvc的开发原则进行开发。
  • Iris框架支持请求数据、模型、持久数据分层处理,并支持各层级模块代码绑定执行。
  • MVC即:modelviewcontroller三个部分,分别代表数据层、视图层、控制层。控制器层负责完成页面逻辑、实体层负责完成数据准备与数据操作、视图层负责展现UI效果。
    :::

1 mvc.Application

iris框架中的mvc包中提供了Application结构体定义。开发者可以通过注册自定义的controller来使用对应提供的API,其中包含路由组router.Party,以此用来注册layout、middleware以及相应的handlers等。

2 iris.mvc特性

iris框架封装的mvc包,支持所有的http方法。比如,如果想要提供GET,那么控制器应该有一个名为Get()的函数,开发者可以定义多个方法函数在同一个Controller中提供。这里的Get、Post方法是指的直接和八种请求类型同名的方法,mvc模块会自动执行到Get()、Post()等八种对应的方法。如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
go复制代码package main

import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
)
//自定义的控制器
type CustomController struct{}

//自动处理基础的Http请求
//Url: http://localhost:8000
//Type:GET请求
func (cc *CustomController) Get() mvc.Result{
//todo
return mvc.Response{
ContentType:"text/html",
}
}
/**
* Url:http://localhost:8000
* Type:POST
**/
func (cc *CustomController) Post() mvc.Result{
//todo
return mvc.Response{}
}
func main() {
app := iris.New()
//注册自定义控制器处理请求
mvc.New(app).Handle(new(CustomController))
app.Run(iris.Addr(":8085"))
}

3 MVC使用中间件示例

main包显示了如何将中间件添加到mvc应用程序中,
使用它的Router,它是主iris app的子路由器(iris.Party)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
go复制代码package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/cache"
"github.com/kataras/iris/v12/mvc"
"time"
)
var cacheHandler = cache.Handler(10 * time.Second)
func main() {
app := iris.New()
mvc.Configure(app, configure)
// http://localhost:8080
// http://localhost:8080/other
// 每10秒刷新一次,你会看到不同的时间输出。
app.Run(iris.Addr(":8080"))
}
func configure(m *mvc.Application) {
m.Router.Use(cacheHandler)
m.Handle(&exampleController{
timeFormat: "2006-01-02 15:04:05",
})
}
type exampleController struct {
timeFormat string
}
func (c *exampleController) Get() string {
now := time.Now().Format(c.timeFormat)
return "last time executed without cache: " + now
}
func (c *exampleController) GetOther() string {
now := time.Now().Format(c.timeFormat)
return "/other: " + now
}

4 整体代码示例

4.1 main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
go复制代码package main

import (
"fmt"
"github.com/kataras/iris/v12"
"pathway/utils"
"pathway/web/models"
"pathway/web/routers"
)

func main() {
app := iris.Default()
models.InitDataBase() //初始化数据库
routers.Register(app) //注册路由
fmt.Println("程序启动")
}

4.2 routers.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
go复制代码package routers

import (
"pathway/sentacom"
"pathway/utils"
"pathway/web/common"
"pathway/web/controller"
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
)

func Register(app *iris.Application) {
fmt.Println("接口初始化中...")
//处理iris跨域
app.Use(common.AllowCRS)
app.AllowMethods(iris.MethodOptions)
//路径分组
mvc.New(app.Party("/pathway/path/group")).Handle(controller.NewPathGroupController())
//路径分组-->PathItem路径项
mvc.New(app.Party("/pathway/path/item")).Handle(controller.NewPathItemController())

//读取配置文件数据
config := utils.GetConfig()
serveHost := config.Serve.Host
serveport := config.Serve.Port
strAddr := fmt.Sprintf("%s:%v", serveHost, serveport) //服务启动的ip:port
app.Run(iris.Addr(strAddr))

}

4.3 controller.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
go复制代码package controller

import (
"pathway/sentacom"
"pathway/web/common"
"pathway/web/models"
"pathway/web/service"
"github.com/kataras/iris/v12"
"net/http"
"reflect"
)

//PathGroupController
type PathGroupController struct {
Ctx iris.Context //上下文对象
Service service.PathGroupService //操作数据库service层
}
//定义route调用的方法
func NewPathGroupController() *PathGroupController {
return &PathGroupController{Service: service.NewPathGroupService()}
}

//请求方式为 POST 请求url:ip:port/pathway/path/group
func (g *PathGroupController) Post() (result common.ResultData) {
var group models.PathGroup
//读取前端传递过来的json数据
if err := g.Ctx.ReadJSON(&group); err != nil {
return common.ResponseErrorResult(err.Error(), http.StatusBadRequest)
}
//调用service层处理业务逻辑
ret, err := g.Service.SavePathGroup(group)
if err != nil {
return common.ResponseErrorResult(err.Error(), http.StatusBadRequest)
}
return common.ResponseResult(ret, http.StatusOK, sentacom.SuccessText(sentacom.AddSuccess))
}

//请求方式为 GET 请求url:ip:port/pathway/path/group
func (g *PathGroupController) Get() (result common.ResultData) {
//此处省略Get处理的方法
}

func (g *PathGroupController) Put() (result common.ResultData) {
//此处省略Put处理的方法
}

func (g *PathGroupController) Delete() (result common.ResultData) {
//此处省略Delete处理的方法
}

4.4 common.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
go复制代码package common

import "pathway/sentacom"

type ResultData struct {
Status int `json:"status"` //HTTP响应状态码
Msg string `json:"msg"` //返回的提示消息
Data interface{} `json:"data"` // HTTP响应数据
}

// 封装http请求统一返回的数据结构
//
// ResponseResult(err.Error(), 604, "查询失败")
func ResponseResult(data interface{}, status int, msg string) ResultData {
return ResultData{
Status: status,
Msg: msg,
Data: data,
}
}

// 封装http请求统一返回的错误数据结构
//
// ResponseResult(err.Error(), 604)
func ResponseErrorResult(data interface{}, httpStatus int) ResultData {
msg := sentacom.ErrorText(httpStatus)
return ResultData{
Status: httpStatus,
Msg: msg,
Data: data,
}
}

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%