Iris框架入门

MVC是什么?

  • Model(模型):它是应用程序的主体部分,主要包括业务逻辑,数据操作和数据模型

  • View(视图):用户与之交互的界面

  • Controller(控制器):接收来自界面的请求并交给模型进行处理

MVC工作流程

目录结构

├── datamodels
├── repositories
├── services
└── web
    ├── controllers
    ├── views
    └── main.go

RUNING起来

入口函数

package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/mvc"
    "../web/controllers"
)

func main() {
    //1.创建Iris框架
    app := iris.New()
    //2.设置日志等级debug模式
    app.Logger().SetLevel("debug")
    //3.注册模板
    app.RegisterView(iris.HTML("./web/views",".html"))
    //4.其他初始化操作,如数据库seesion等

    //5.注册控制器
    mvc.New(app.Party("/hello")).Handle(new(controllers.MovieController))
    //6.启动服务
    _ = app.Run(
        //启动服务监听端口
        iris.Addr("localhost:8080"),
        //忽略服务器错误
        iris.WithoutServerError(iris.ErrServerClosed),
        //让程序自身尽可能的优化
        iris.WithOptimizations,
        )
}

services

package services
import (
    "../repositories"
    "log"
)

type MovieService interface {
    ShowMovieName() string
}

type MovieServiceManger struct {
    repo repositories.MovieRepository
}

func NewMovieServiceManager(repo repositories.MovieRepository) MovieService {
    return &MovieServiceManger{repo:repo}
}

func (m *MovieServiceManger) ShowMovieName() string{
    log.Println("获取到的视频名称",m.repo.GetMovieName())
    return "获取到的视频名称"+m.repo.GetMovieName()
}

repositories

package repositories

import "github.com/kataras/iris/_examples/mvc/overview/datamodels"

type MovieRepository interface {
    GetMovieName() string
}

type MovieManager struct {

}

func NewMovieManager() MovieRepository{
    return &MovieManager{}
}

func (m *MovieManager) GetMovieName() string{
    //模拟赋值给结构体
    movie := &datamodels.Movie{Name:"兄Die牛逼"}
    return movie.Name
}

controllers

package controllers

import (
    "../../repositories"
    "../../services"
    "github.com/kataras/iris/mvc"
)

type MovieController struct {

}

func (c *MovieController) Get() mvc.View {
    movieReponsitory := repositories.NewMovieManager()
    movieService := services.NewMovieServiceManager(movieReponsitory)
    movieResult := movieService.ShowMovieName()
    //控制器渲染模板
    return mvc.View{
        Name:"movie/index.html",
        Data:movieResult,
    }
}
  • 然后go run main.go即可

Iris框架入门》有1个想法

发表评论

电子邮件地址不会被公开。 必填项已用*标注