Documentation
_assets/web_mvc_diagram.png
Using Iris MVC for code reuse.
By creating components that are independent of one another, developers are able to reuse components quickly and easily in other applications. The same (or similar) view for one application can be refactored for another application with different data because the view is simply handling how the data is being displayed to the user.
Iris has first-class support for the MVC (Model View Controller) architectural pattern, you'll not find these stuff anywhere else in the Go world. You will have to import the iris/mvc subpackage.
1
import "github.com/kataras/iris/v12/mvc"
Copied!
Iris web framework supports Request data, Models, Persistence Data and Binding with the fastest possible execution.
If you're new to back-end web development read about the MVC architectural pattern first, a good start is that wikipedia article.
Note: Read the Dependency Injection section before continue.
Characteristics
All HTTP Methods are supported, for example if want to serve GET then the controller should have a function named Get(), for POST verb use the Post(), for a parameter use the By keyword, e.g. PostUserBy(id uint64) which translates to POST: [...]/User/{id}.
Serve custom controller's struct's methods as handlers with custom paths(even with regex parametermized path) via the BeforeActivation custom event callback, per-controller. Example:
1
import (
2
"github.com/kataras/iris/v12"
3
"github.com/kataras/iris/v12/mvc"
4
)
5
6
func main() {
7
app := iris.New()
8
mvc.Configure(app.Party("/root"), myMVC)
9
app.Listen(":8080")
10
}
11
12
func myMVC(app *mvc.Application) {
13
// app.Register(...)
14
// app.Router.Use/UseGlobal/Done(...)
15
app.Handle(new(MyController))
16
}
17
18
type MyController struct {}
19
20
func (m *MyController) BeforeActivation(b mvc.BeforeActivation) {
21
// b.Dependencies().Add/Remove
22
// b.Router().Use/UseGlobal/Done
23
// and any standard Router API call you already know
24
25
// 1-> Method
26
// 2-> Path
27
// 3-> The controller's function name to be parsed as handler
28
// 4-> Any handlers that should run before the MyCustomHandler
29
b.Handle("GET", "/something/{id:int64}", "MyCustomHandler", anyMiddleware...)
30
}
31
32
// GET: http://localhost:8080/root
33
func (m *MyController) Get() string {
34
return "Hey"
35
}
36
37
// GET: http://localhost:8080/root/something/{id:int64}
38
func (m *MyController) MyCustomHandler(id int64) string {
39
return "MyCustomHandler says Hey"
40
}
Copied!
Persistence data inside your Controller struct (share data between requests) by defining services to the Dependencies or have a Singleton controller scope.
Share the dependencies between controllers or register them on a parent MVC Application, and ability to modify dependencies per-controller on the BeforeActivation optional event callback inside a Controller, i.e func(c *MyController) BeforeActivation(b mvc.BeforeActivation) { b.Dependencies().Add/Remove(...) }.
Access to the Context as a controller's field(no manual binding is neede) i.e Ctx iris.Context or via a method's input argument, i.e func(ctx iris.Context, otherArguments...).
Models inside your Controller struct (set-ed at the Method function and rendered by the View). You can return models from a controller's method or set a field in the request lifecycle and return that field to another method, in the same request lifecycle.
Flow as you used to, mvc application has its own Router which is a type of iris/router.Party, the standard iris api. Controllers can be registered to any Party, including Subdomains, the Party's begin and done handlers work as expected.
Optional BeginRequest(ctx) function to perform any initialization before the method execution, useful to call middlewares or when many methods use the same collection of data.
Optional EndRequest(ctx) function to perform any finalization after any method executed.
Inheritance, recursively, e.g. our mvc session-controller example, has the Session *sessions.Session as struct field which is filled by the sessions manager.
Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed. When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods with the By word, uppercase is a new sub path. Example:
If mvc.New(app.Party("/user")).Handle(new(user.Controller))
    func(*Controller) Get() - GET:/user.
    func(*Controller) Post() - POST:/user.
    func(*Controller) GetLogin() - GET:/user/login
    func(*Controller) PostLogin() - POST:/user/login
    func(*Controller) GetProfileFollowers() - GET:/user/profile/followers
    func(*Controller) PostProfileFollowers() - POST:/user/profile/followers
    func(*Controller) GetBy(id int64) - GET:/user/{param:int64}
    func(*Controller) PostBy(id int64) - POST:/user/{param:int64}
If mvc.New(app.Party("/profile")).Handle(new(profile.Controller))
    func(*Controller) GetBy(username string) - GET:/profile/{param:string}
If mvc.New(app.Party("/assets")).Handle(new(file.Controller))
    func(*Controller) GetByWildcard(path string) - GET:/assets/{param:path}
    Supported types for method functions receivers: int, int64, bool and string.
Optionally, response via output arguments, like we've shown at the Dependency Injection chapter. E.g.
1
func(c *ExampleController) Get() string |
2
(string, string) |
3
(string, int) |
4
int |
5
(int, string) |
6
(string, error) |
7
error |
8
(int, error) |
9
(any, bool) |
10
(customStruct, error) |
11
customStruct |
12
(customStruct, int) |
13
(customStruct, string) |
14
mvc.Result or (mvc.Result, error)
Copied!
Where mvc.Result is just a type alias of hero.Result:
1
type Result interface {
2
// Dispatch should sends the response to the context's response writer.
3
Dispatch(ctx iris.Context)
4
}
Copied!

Example

This example is equivalent to a simple hello world application.
It seems that additional code you have to write doesn't worth it but remember that, this example does not make use of iris mvc features like the Model, Persistence or the View engine neither the Session, it's very simple for learning purposes, probably you'll never use such as simple controller anywhere in your app.
The cost we have on this example for using MVC on the "/hello" path which serves JSON is ~2MB per 20MB throughput on my personal laptop, it's tolerated for the majority of the applications but you can choose what suits you best with Iris, low-level handlers: performance or high-level controllers: easier to maintain and smaller codebase on large applications.
Read the comments carefully
1
package main
2
3
import (
4
"github.com/kataras/iris/v12"
5
"github.com/kataras/iris/v12/mvc"
6
7
"github.com/kataras/iris/v12/middleware/logger"
8
"github.com/kataras/iris/v12/middleware/recover"
9
)
10
11
func main() {
12
app := iris.New()
13
// Optionally, add two built'n handlers
14
// that can recover from any http-relative panics
15
// and log the requests to the terminal.
16
app.Use(recover.New())
17
app.Use(logger.New())
18
19
// Serve a controller based on the root Router, "/".
20
mvc.New(app).Handle(new(ExampleController))
21
22
// http://localhost:8080
23
// http://localhost:8080/ping
24
// http://localhost:8080/hello
25
// http://localhost:8080/custom_path
26
app.Listen(":8080")
27
}
28
29
// ExampleController serves the "/", "/ping" and "/hello".
30
type ExampleController struct{}
31
32
// Get serves
33
// Method: GET
34
// Resource: http://localhost:8080
35
func (c *ExampleController) Get() mvc.Result {
36
return mvc.Response{
37
ContentType: "text/html",
38
Text: "<h1>Welcome</h1>",
39
}
40
}
41
42
// GetPing serves
43
// Method: GET
44
// Resource: http://localhost:8080/ping
45
func (c *ExampleController) GetPing() string {
46
return "pong"
47
}
48
49
// GetHello serves
50
// Method: GET
51
// Resource: http://localhost:8080/hello
52
func (c *ExampleController) GetHello() interface{} {
53
return map[string]string{"message": "Hello Iris!"}
54
}
55
56
// BeforeActivation called once, before the controller adapted to the main application
57
// and of course before the server ran.
58
// After version 9 you can also add custom routes for a specific controller's methods.
59
// Here you can register custom method's handlers
60
// use the standard router with `ca.Router` to
61
// do something that you can do without mvc as well,
62
// and add dependencies that will be binded to
63
// a controller's fields or method function's input arguments.
64
func (c *ExampleController) BeforeActivation(b mvc.BeforeActivation) {
65
anyMiddlewareHere := func(ctx iris.Context) {
66
ctx.Application().Logger().Warnf("Inside /custom_path")
67
ctx.Next()
68
}
69
70
b.Handle(
71
"GET",
72
"/custom_path",
73
"CustomHandlerWithoutFollowingTheNamingGuide",
74
anyMiddlewareHere,
75
)
76
77
// or even add a global middleware based on this controller's router,
78
// which in this example is the root "/":
79
// b.Router().Use(myMiddleware)
80
}
81
82
// CustomHandlerWithoutFollowingTheNamingGuide serves
83
// Method: GET
84
// Resource: http://localhost:8080/custom_path
85
func (c *ExampleController) CustomHandlerWithoutFollowingTheNamingGuide() string {
86
return "hello from the custom handler without following the naming guide"
87
}
88
89
// GetUserBy serves
90
// Method: GET
91
// Resource: http://localhost:8080/user/{username:string}
92
// By is a reserved "keyword" to tell the framework that you're going to
93
// bind path parameters in the function's input arguments, and it also
94
// helps to have "Get" and "GetBy" in the same controller.
95
//
96
// func (c *ExampleController) GetUserBy(username string) mvc.Result {
97
// return mvc.View{
98
// Name: "user/username.html",
99
// Data: username,
100
// }
101
// }
102
103
/* Can use more than one, the factory will make sure
104
that the correct http methods are being registered for each route
105
for this controller, uncomment these if you want:
106
107
func (c *ExampleController) Post() {}
108
func (c *ExampleController) Put() {}
109
func (c *ExampleController) Delete() {}
110
func (c *ExampleController) Connect() {}
111
func (c *ExampleController) Head() {}
112
func (c *ExampleController) Patch() {}
113
func (c *ExampleController) Options() {}
114
func (c *ExampleController) Trace() {}
115
*/
116
117
/*
118
func (c *ExampleController) All() {}
119
// OR
120
func (c *ExampleController) Any() {}
121
122
123
124
func (c *ExampleController) BeforeActivation(b mvc.BeforeActivation) {
125
// 1 -> the HTTP Method
126
// 2 -> the route's path
127
// 3 -> this controller's method name that should be handler for that route.
128
b.Handle("GET", "/mypath/{param}", "DoIt", optionalMiddlewareHere...)
129
}
130
131
// After activation, all dependencies are set-ed - so read only access on them
132
// but still possible to add custom controller or simple standard handlers.
133
func (c *ExampleController) AfterActivation(a mvc.AfterActivation) {}
134
135
*/
Copied!
Every exported func prefixed with an HTTP Method(Get, Post, Put, Delete...) in a controller is callable as an HTTP endpoint. In the sample above, all funcs writes a string to the response. Note the comments preceding each method.
An HTTP endpoint is a targetable URL in the web application, such as http://localhost:8080/helloworld, and combines the protocol used: HTTP, the network location of the web server (including the TCP port): localhost:8080 and the target URI /helloworld.
The first comment states this is an HTTP GET method that is invoked by appending "/helloworld" to the base URL. The third comment specifies an HTTP GET method that is invoked by appending "/helloworld/welcome" to the URL.
Controller knows how to handle the "name" on GetBy or the "name" and "numTimes" at GetWelcomeBy, because of the By keyword, and builds the dynamic route without boilerplate; the third comment specifies an HTTP GET dynamic method that is invoked by any URL that starts with "/helloworld/welcome" and followed by two more path parts, the first one can accept any value and the second can accept only numbers, i,e: "http://localhost:8080/helloworld/welcome/golang/32719", otherwise a 404 Not Found HTTP Error will be sent to the client instead.
The _examples/mvc and mvc/controller_test.go files explain each feature with simple paradigms, they show how you can take advandage of the Iris MVC Binder, Iris MVC Models and more...
Last modified 1yr ago
Export as PDF
Copy link
Contents
Example