-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
main.go
85 lines (65 loc) · 1.37 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
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"github.com/kataras/iris/v12"
)
func main() {
app := newApp()
// GET: http://localhost:8080
app.Listen(":8080")
}
func newApp() *iris.Application {
app := iris.New()
app.Use(middleware)
// OR app.UseRouter(middleware)
// to register it everywhere,
// including the HTTP errors.
app.Get("/", handler)
return app
}
func middleware(ctx iris.Context) {
service := &helloService{
Greeting: "Hello",
}
setService(ctx, service)
ctx.Next()
}
func handler(ctx iris.Context) {
service, ok := getService(ctx)
if !ok {
ctx.StopWithStatus(iris.StatusInternalServerError)
return
}
response := service.Greet("Gophers")
ctx.WriteString(response)
}
/*
| ---------------------- |
| service implementation |
| ---------------------- |
*/
const serviceContextKey = "app.service"
func setService(ctx iris.Context, service GreetService) {
ctx.Values().Set(serviceContextKey, service)
}
func getService(ctx iris.Context) (GreetService, bool) {
v := ctx.Values().Get(serviceContextKey)
if v == nil {
return nil, false
}
service, ok := v.(GreetService)
if !ok {
return nil, false
}
return service, true
}
// A GreetService example.
type GreetService interface {
Greet(name string) string
}
type helloService struct {
Greeting string
}
func (m *helloService) Greet(name string) string {
return fmt.Sprintf("%s, %s!", m.Greeting, name)
}