“This is the 16th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

::: tip Overview of the MVC package

  • inIrisIn the framework, encapsulatedmvcPackage as tomvcArchitecture support for easy developers to followmvcDevelopment principles for development.
  • IrisThe framework supports hierarchical processing of request data, model and persistent data, as well as binding execution of module code at all levels.
  • MVCThat is:model,view,controllerThree parts, representing data layer, view layer and control layer respectively. The controller layer is responsible for page logic, the entity layer is responsible for data preparation and data operation, and the view layer is responsible for displaying UI effects.

: : :

1 mvc.Application

The Application structure definition is provided in the MVC package in the IRIS framework. Developers can use the API provided by registering custom Controllers, including the router.Party routing group, to register layouts, Middleware, handlers, and so on.

2 iris. MVC features

The MVC package encapsulated by the Iris framework supports all HTTP methods. For example, if you want to provide GET, the Controller should have a function called GET (). Developers can define multiple method functions to provide in the same Controller. Here Get and Post methods refer to methods with the same name as the eight request types directly. MVC module will automatically execute eight corresponding methods such as Get() and Post(). As follows:

package main

import (
   "github.com/kataras/iris/v12"
   "github.com/kataras/iris/v12/mvc"
)
// Custom controller
type CustomController struct{}

// Handle basic Http requests automatically
/ / Url: http://localhost:8000
//Type: GET request
func (cc *CustomController) Get(a) mvc.Result{
   //todo
   return mvc.Response{
   	ContentType:"text/html",}}/** * Url: http://localhost:8000 * Type: POST **/
func (cc *CustomController) Post(a) mvc.Result{
   //todo
   return mvc.Response{}
}
func main(a) {
   app := iris.New()
   // Register the custom controller to process requests
   mvc.New(app).Handle(new(CustomController))
   app.Run(iris.Addr(": 8085"))}Copy the code

Example of MVC using middleware

The main package shows how to add middleware to an MVC application,

Use its Router, which is a child Router of the main Iris app (iris.party).

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(a) {
	app := iris.New()
	mvc.Configure(app, configure)
	// http://localhost:8080
	// http://localhost:8080/other
	// Refresh every 10 seconds and you will see different time output.
	app.Run(iris.Addr(": 8080"))}func configure(m *mvc.Application) {
	m.Router.Use(cacheHandler)
	m.Handle(&exampleController{
		timeFormat: "The 2006-01-02 15:04:05"})},type exampleController struct {
	timeFormat string
}
func (c *exampleController) Get(a) string {
	now := time.Now().Format(c.timeFormat)
	return "last time executed without cache: " + now
}
func (c *exampleController) GetOther(a) string {
	now := time.Now().Format(c.timeFormat)
	return "/other: " + now
}
Copy the code

4 Overall code examples

4.1 the main. Go

package main

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

func main(a) {
	app := iris.Default()
    models.InitDataBase() // Initialize the database
	routers.Register(app) // Register the route
	fmt.Println("Program start")}Copy the code

4.2 routers. 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("Initializing interface...")
    // Handle IRIS across domains
	app.Use(common.AllowCRS) 
	app.AllowMethods(iris.MethodOptions)
	// Path grouping
	mvc.New(app.Party("/pathway/path/group")).Handle(controller.NewPathGroupController())
	// path group -->PathItem PathItem
	mvc.New(app.Party("/pathway/path/item")).Handle(controller.NewPathItemController())

    // Read configuration file data
	config := utils.GetConfig()
	serveHost := config.Serve.Host
	serveport := config.Serve.Port
	strAddr := fmt.Sprintf("%s:%v", serveHost, serveport) // Service startup IP :port
	app.Run(iris.Addr(strAddr))

}
Copy the code

4.3 controller. 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  // Context object
	Service service.PathGroupService // Operate the database service layer
}
// Define the method called by route
func NewPathGroupController(a) *PathGroupController {
	return &PathGroupController{Service: service.NewPathGroupService()}
}

/ / request way as the POST request url: IP: port/pathway/path/group
func (g *PathGroupController) Post(a) (result common.ResultData) {
	var group models.PathGroup
        // Read the json data from the front end
	iferr := g.Ctx.ReadJSON(&group); err ! =nil {
		return common.ResponseErrorResult(err.Error(), http.StatusBadRequest)
	}
    // Call the Service layer to handle the business logic
	ret, err := g.Service.SavePathGroup(group)
	iferr ! =nil {
		return common.ResponseErrorResult(err.Error(), http.StatusBadRequest)
	}
	return common.ResponseResult(ret, http.StatusOK, sentacom.SuccessText(sentacom.AddSuccess))
}

/ / request method to GET request url: IP: port/pathway/path/group
func (g *PathGroupController) Get(a) (result common.ResultData) {
        // Omit the Get method here
}

func (g *PathGroupController) Put(a) (result common.ResultData) {
		// Omit the Put method here
}

func (g *PathGroupController) Delete(a) (result common.ResultData) {
	// Omit the Delete handler here
}
Copy the code

4.4 common. Go

package common

import "pathway/sentacom"

type ResultData struct {
	Status int         `json:"status"` //HTTP response status code
	Msg    string      `json:"msg"`    // A prompt message is returned
	Data   interface{} `json:"data"`   // HTTP response data
}

// Encapsulate the data structure uniformly returned by HTTP requests
//
// ResponseResult(err.error (), 604, "Error ")
func ResponseResult(data interface{}, status int, msg string) ResultData {
	return ResultData{
		Status: status,
		Msg:    msg,
		Data:   data,
	}
}

// Encapsulate the error data structure that HTTP requests uniformly return
//
// ResponseResult(err.Error(), 604)
func ResponseErrorResult(data interface{}, httpStatus int) ResultData {
	msg := sentacom.ErrorText(httpStatus)
	return ResultData{
		Status: httpStatus,
		Msg:    msg,
		Data:   data,
	}
}
Copy the code