Iris 框架
官网:https://iris-go.com 框架文档:https://github.com/iris-contrib/examples
目录结构
手动创建一个mvc目录结构
「M」
- datamodels:只存放结构体
- repositories:数据库相关操作文件
- services:业务逻辑 以上三个文件夹可以综合为M层
- web
- controllers :控制器层 「C」
- views :视图层 「V」
下载Iris框架:go get github.com/kataras/iris/v12@master
入口文件
入口文件为根目录下 main.go
main.go :
代码语言:javascript复制package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"iris/web/controllers"
)
func main() {
//新建iris
app:=iris.New()
//设置错误等级
app.Logger().SetLevel("debug")
//注册模板目录
app.RegisterView(iris.HTML("./web/views",".html"))
//注册控制器
mvc.New(app.Party("/hello")).Handle(new(controllers.BookController))
//启动服务
app.Run(
iris.Addr("localhost:8080"), //监听8080端口
)
}
datamodelsbook.go
代码语言:javascript复制package datamodels
type Book struct {
Name string
}
repositoriesbook_repository.go
代码语言:javascript复制package repositories
import "iris/datamodels"
type BookRepository interface {
GetBookName() string
}
type BookManager struct {
}
func NewBookManager() BookRepository {
return &BookManager{}
}
func (m *BookManager) GetBookName() string {
//模拟赋值给模型
book := &datamodels.Book{Name: "微客鸟窝"}
return book.Name
}
servicesbook_service.go
代码语言:javascript复制package services
import (
"fmt"
"iris/repositories"
)
type BookService interface {
ShowBookName() string
}
type BookServiceManger struct {
repo repositories.BookRepository
}
func NewBookServiceManger(repo repositories.BookRepository) BookService {
return &BookServiceManger{repo:repo}
}
func (m *BookServiceManger) ShowBookName() string {
fmt.Println("获取的名称为:" m.repo.GetBookName())
return "获取的名称为:" m.repo.GetBookName()
}
webcontrollersbook_controller.go
代码语言:javascript复制package controllers
import (
"github.com/kataras/iris/v12/mvc"
"iris/repositories"
"iris/services"
)
type BookController struct{
}
func (c *BookController) Get() mvc.View {
bookRepository := repositories.NewBookManager()
bookService := services.NewBookServiceManger(bookRepository)
BookResult := bookService.ShowBookName()
return mvc.View{ //渲染模板
Name:"/book/index.html",
Data:BookResult,
}
}
webviewsbookindex.html
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>{{.}}</h2>
</body>
</html>
运行go run main.go
浏览器访问 http://localhost:8080/hello
一个简单的 iris mvc 例子就此完成。希望对诸位有所帮助。