go初识iris框架(五) -MVC包的使用

在Iris框架中,封装了mvc包作为对mvc架构的支持,方便开发者遵循mvc的开发原则进行开发。

iis框架支持请求数据、模型、持久数据分层处理,并支持各层级模块代码绑定执行。
MVC即:model、view、controller三个部分,分别代表数据层、视图层、控制层。控制器层负责完

成页面逐辑、实体层负责完成数据准备与数据操作、视图层负责展现U效果。

mvc.Application

iris框架中的mvc包中提供了Application:结构体定义。开发者可以通过注册自定义的controller:来使用

对应提供的APL,其中包含路由组router.Party,.以此用来注册layout、middlewarel(中间件)以及相应的

handlers等。

iris.mvc特性

iris框架封装的mvc包,支持所有的http方法。比如,如果想要提供GET,那么控制器应该有一个名为

Get()的函数,开发者可以定义多个方法函数在同一个Controller中提供。这里的Get、Post方法是

指的直接和八种请求类型同名的方法,mvc模块会自动执行到Get()、Post()等八种对应的方法。

示例

Get请求

go 复制代码
package main

import "github.com/kataras/iris/v12"
import "github.com/kataras/iris/v12/mvc"

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

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

	app.Run(iris.Addr(":8088"))
}

type UserController struct{
	//这里面的内容可以随便填写
}

/*
  url: http://localhost:8088
  type: Get
*/
func (uc *UserController) Get() string {
	return "hello world"
}

若出现以下报错

可以执行一下命令来解决

shell 复制代码
go get github.com/kataras/iris/v12/versioning@v12.2.5
shell 复制代码
go get github.com/kataras/iris/v12/websocket@v12.2.5

Post请求

go 复制代码
/*
  url: http://localhost:8088
  type: Post
*/
func (uc *UserController) Post() {
	iris.New().Logger().Info("post请求")
}

根据请求的类型和请求的URL自动匹配处理方式

go 复制代码
/*
  url: http://localhost:8088/info
  type: Get
*/
func (uc *UserController) GetInfo() mvc.Result{
	//todo
	return mvc.Response{
		Object: map[string] interface{}{
			"code": 200,
			"message":"请求成功",
		},
	}
}

/*
  url: http://localhost:8088/login
  type: Post
*/
func (uc *UserController) PostLogin() mvc.Result{
	//todo
	return mvc.Response{
		Object: map[string] interface{}{
			"code": 200,
			"message":"请求成功",
		},
	}
}

这里的Get请求(来自于本地)
返回值mvc.Result:属于是mvc的一种请求的返回类型
注意自动匹配格式请求+URL的方式比如GetInfo就是Get请求的/info

BeforeActivation方法

人为手动指定

go 复制代码
/*
url:  http://localhost:8088/query
type:Get
*/
func (uc *UserController) BeforeActivation(a mvc.BeforeActivation) {
	a.Handle("Get", "/query", "UserInfo") //Handle(httpMethod:请求类型,path:请求路径,funcName:这个方法处理这个http请求)
}
func (uc *UserController) UserInfo() mvc.Result {
	return mvc.Response{}
}

路由组的mvc处理

go 复制代码
//路由组的mvc处理
mvc.Configure(app.Party("/user"), func(ctx *mvc.Application) {
	ctx.Handle(new(UserController))
})
相关推荐
刀法如飞11 天前
一款Go语言Gin框架MVC脚手架,满足大部分场景
go·mvc·gin
花酒锄作田12 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理12 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12312 天前
matlab画图工具
开发语言·matlab
dustcell.12 天前
haproxy七层代理
java·开发语言·前端
norlan_jame12 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone12 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549612 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月12 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js