Iris: How I can parse data from body

Created on 9 Feb 2018  路  2Comments  路  Source: kataras/iris

I have an api to post users. for Body my data is [{"name": "ABC", "age":20}, {"name":"XYZ", "age":23}]

app.Post("/Users", func(ctx iris.Context) {
})

How i can parse and get data from ctx

help-needed

Most helpful comment

Thanks @kataras for quick response and for wonderful framework, I will check examples before creating issue 鈽曪笍

All 2 comments

Hello, that's why I always recommend that you (new gophers) have to learn net/http first before moving to any framework. This is documented, please read the _examples. I will provide you the code, it's your first issue after all so you are forgiven :P

package main

import "github.com/kataras/iris"

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

// MyHandler reads a collection of Person from JSON post body.
func MyHandler(ctx iris.Context) {
    var persons []Person
    err := ctx.ReadJSON(&persons)

    if err != nil {
        ctx.StatusCode(iris.StatusBadRequest)
        ctx.WriteString(err.Error())
        return
    }

    ctx.Writef("Received: %#+v\n", persons)
}

func main() {
    app := iris.New()
    app.Post("/", MyHandler)

    // use Postman or whatever to do a POST request
    // to the http://localhost:8080 with RAW BODY:
        // [{"name": "ABC", "age":20}, {"name":"XYZ", "age":23}]
    // and Content-Type to application/json
    //
    // The response should be:
    // Received: []main.Person{main.Person{Name:"ABC", Age:20}, main.Person{Name:"XYZ", Age:23}}

    app.Run(iris.Addr(":8080"))
}

Feel free to post any further questions and thanks for using Iris!

Thanks @kataras for quick response and for wonderful framework, I will check examples before creating issue 鈽曪笍

Was this page helpful?
0 / 5 - 0 ratings