mirror of
https://github.com/kataras/iris.git
synced 2025-02-03 07:50:34 +01:00
89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"github.com/kataras/iris/v12"
|
||
|
"github.com/kataras/iris/v12/context"
|
||
|
)
|
||
|
|
||
|
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,
|
||
|
})
|
||
|
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 context.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, context.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,
|
||
|
})
|
||
|
}
|