-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
main.go
86 lines (72 loc) · 1.85 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
86
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Post("/", postIndex)
app.Post("/stream", postIndexStream)
/*
curl -L -X POST "http://localhost:8080/" \
-H 'Content-Type: application/json' \
--data-raw '{"username":"john"}'
curl -L -X POST "http://localhost:8080/stream" \
-H 'Content-Type: application/json' \
--data-raw '{"username":"john"}
{"username":"makis"}
{"username":"george"}
{"username":"michael"}
'
If JSONReader.ArrayStream was true then you must provide an array of objects instead, e.g.
[{"username":"john"},
{"username":"makis"},
{"username":"george"},
{"username":"michael"}]
*/
app.Listen(":8080")
}
type User struct {
Username string `json:"username"`
}
func postIndex(ctx iris.Context) {
var u User
err := ctx.ReadJSON(&u, iris.JSONReader{
// To throw an error on unknown request payload json fields.
DisallowUnknownFields: true,
Optimize: true,
})
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.JSON(iris.Map{
"code": iris.StatusOK,
"username": u.Username,
})
}
func postIndexStream(ctx iris.Context) {
var users []User
job := func(decode iris.DecodeFunc) error {
var u User
if err := decode(&u); err != nil {
return err
}
users = append(users, u)
// When the returned error is not nil the decode operation
// is terminated and the error is received by the ReadJSONStream method below,
// otherwise it continues to read the next available object.
return nil
}
err := ctx.ReadJSONStream(job, iris.JSONReader{
Optimize: true,
DisallowUnknownFields: true,
ArrayStream: false,
})
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.JSON(iris.Map{
"code": iris.StatusOK,
"users_count": len(users),
"users": users,
})
}