iris/_examples/request-body/read-json/main.go
Gerasimos (Makis) Maropoulos ed45c77be5 reorganization of _examples and add some new examples such as iris+groupcache+mysql+docker
Former-commit-id: ed635ee95de7160cde11eaabc0c1dcb0e460a620
2020-06-07 15:26:06 +03:00

63 lines
1.2 KiB
Go

package main
import (
"github.com/kataras/iris/v12"
)
type Company struct {
Name string
City string
Other string
}
func MyHandler(ctx iris.Context) {
var c Company
if err := ctx.ReadJSON(&c); err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.Writef("Received: %#+v\n", c)
}
// simple json stuff, read more at https://golang.org/pkg/encoding/json
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
// MyHandler2 reads a collection of Person from JSON post body.
func MyHandler2(ctx iris.Context) {
var persons []Person
err := ctx.ReadJSON(&persons)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.Writef("Received: %#+v\n", persons)
}
func main() {
app := iris.New()
app.Post("/", MyHandler)
app.Post("/slice", MyHandler2)
// use Postman or whatever to do a POST request
// to the http://localhost:8080 with RAW BODY:
/*
{
"Name": "iris-Go",
"City": "New York",
"Other": "Something here"
}
*/
// and Content-Type to application/json (optionally but good practise)
//
// The response should be:
// Received: main.Company{Name:"iris-Go", City:"New York", Other:"Something here"}
app.Listen(":8080", iris.WithOptimizations)
}