forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iris.go
123 lines (100 loc) · 2.42 KB
/
iris.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package examples
import (
"fmt"
"io"
"net/http"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/basicauth"
"github.com/kataras/iris/v12/sessions"
)
// IrisHandler tests iris handler
func IrisHandler() http.Handler {
app := iris.New()
sess := sessions.New(sessions.Config{
Cookie: "irissessionid",
})
app.Get("/things", func(ctx iris.Context) {
ctx.JSON([]interface{}{
iris.Map{
"name": "foo",
"description": "foo thing",
},
iris.Map{
"name": "bar",
"description": "bar thing",
},
})
})
app.Post("/redirect", func(ctx iris.Context) {
ctx.Redirect("/things", iris.StatusFound)
})
app.Post("/params/{x}/{y}", func(ctx iris.Context) {
ctx.JSON(iris.Map{
"x": ctx.Params().Get("x"),
"y": ctx.Params().Get("y"),
"q": ctx.URLParam("q"),
"p1": ctx.FormValue("p1"),
"p2": ctx.FormValue("p2"),
})
})
auth := basicauth.Default(map[string]string{
"ford": "betelgeuse7",
})
app.Get("/auth", auth, func(ctx iris.Context) {
ctx.Writef("authenticated!")
})
app.Post("/session/set", func(ctx iris.Context) {
session := sess.Start(ctx)
v := iris.Map{}
if err := ctx.ReadJSON(&v); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
return
}
session.Set("name", v["name"])
})
app.Get("/session/get", func(ctx iris.Context) {
session := sess.Start(ctx)
ctx.JSON(iris.Map{
"name": session.GetString("name"),
})
})
app.Get("/stream", func(ctx iris.Context) {
i := 0
ctx.StreamWriter(func(w io.Writer) error {
if i == 10 {
// causes StreamWriter to stop writing
return io.EOF
} else if _, err := fmt.Fprintf(w, "%d", i); err != nil {
return err
}
i++
// return nil to continue writing
return nil
})
// if we had to write here then the StreamWriter callback should
// return nil instead of EOF
})
app.Post("/stream", func(ctx iris.Context) {
body, err := io.ReadAll(ctx.Request().Body)
if err != nil {
app.Logger().Error(err)
ctx.StatusCode(iris.StatusBadRequest)
ctx.StopExecution()
return
}
ctx.Write(body)
})
sub := app.Subdomain("subdomain")
sub.Post("/set", func(ctx iris.Context) {
session := sess.Start(ctx)
session.Set("message", "hello from subdomain")
})
sub.Get("/get", func(ctx iris.Context) {
session := sess.Start(ctx)
ctx.WriteString(session.GetString("message"))
})
if err := app.Build(); err != nil {
app.Logger().Error(err)
}
return app
}