mirror of
https://github.com/kataras/iris.git
synced 2025-12-18 10:27:06 +00:00
reorganization of _examples and add some new examples such as iris+groupcache+mysql+docker
Former-commit-id: ed635ee95de7160cde11eaabc0c1dcb0e460a620
This commit is contained in:
62
_examples/request-body/read-json/main.go
Normal file
62
_examples/request-body/read-json/main.go
Normal file
@@ -0,0 +1,62 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user