type Person struct {
Name string `json:"name" xml:"name" form:"name"`
Pass string `json:"pass" xml:"pass" form:"pass"`
}
app.Post("/", func(c *fiber.Ctx) error {
p := new(Person)
if err := c.BodyParser(p); err != nil {
return err
}
log.Println(p.Name) // john
log.Println(p.Pass) // doe
// ...
})
Above is the code to Parse a POST
request with a struct. In my case, the number of POST
parameters can be any number. How will it be parsed in that situation?
CodePudding user response:
Curl request for multiple parameters
curl -X POST -H "Content-Type: application/json" --data '[{"name":"john","pass":"doe"},{"name": "jack", "pass":"jill"}]' localhost:3000
Code:
package main
import (
"github.com/gofiber/fiber/v2"
"log"
)
type Person struct {
Name string `json:"name" xml:"name" form:"name"`
Pass string `json:"pass" xml:"pass" form:"pass"`
}
func main() {
app := fiber.New()
app.Post("/", func(c *fiber.Ctx) error {
persons := []Person{}
if err := c.BodyParser(&persons); err != nil {
return err
}
for _, person := range persons {
log.Println(person.Name)
log.Println(person.Pass)
}
log.Println()
return c.SendString("Post Called")
})
app.Listen(":3000")
}
CodePudding user response:
You may find that creating an empty map will work, this code is from enter link description here as follows:
# Using the "str" variable that we created using json.Marshal earlier
var x map[string]interface{}
json.Unmarshal([]byte(str), &x)
fmt.Println("%v", x)
# => %v map[baz:map[bee:boo] foo:bar]
# Using some hand crafted JSON. This could come from a file, web service, anything
str2 := "{"foo":{"baz": [1,2,3]}}"
var y map[string]interface{}
json.Unmarshal([]byte(str2), &y)
fmt.Println("%v", y)
# => %v map[foo:map[baz:[1 2 3]]]
So you would
err = c.BodyParser(str2)
In this example. Hope it helps.