forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (63 loc) · 1.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
)
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html"))
m := mvc.New(app)
m.Handle(new(controller))
app.Listen(":8080")
}
type errorResponse struct {
Code int
Message string
}
/*
// Note: if a struct implements the standard go error, so it's an error
// and its Error() is not empty, then its text will be rendered instead,
// override any Dispatch method.
func (e errorResponse) Error() string {
return e.Message
}
*/
// implements mvc.Result.
func (e errorResponse) Dispatch(ctx iris.Context) {
// If u want to use mvc.Result on any method without an output return value
// go for it:
//
view := mvc.View{Code: e.Code, Data: e} // use Code and Message as the template data.
switch e.Code {
case iris.StatusNotFound:
view.Name = "404"
default:
view.Name = "500"
}
view.Dispatch(ctx)
// Otherwise use ctx methods:
//
// ctx.StatusCode(e.Code)
// switch e.Code {
// case iris.StatusNotFound:
// // use Code and Message as the template data.
// if err := ctx.View("404.html", e)
// default:
// if err := ctx.View("500.html", e)
// }
}
type controller struct{}
type user struct {
ID uint64 `json:"id"`
}
func (c *controller) GetBy(userid uint64) mvc.Result {
if userid != 1 {
return errorResponse{
Code: iris.StatusNotFound,
Message: "User Not Found",
}
}
return mvc.Response{
Object: user{ID: userid},
}
}