Skip to content

Binding json array fails when there is any parm in url #1565

Closed
@blxzfb307

Description

@blxzfb307

Issue Description

I want to bind a json array in the handler function but I can not do it when there is parm in url.
What is the right way to bind json array in the handler function?

Checklist

  • Dependencies installed
  • No typos
  • Searched existing issues and docs

Expected behaviour

curl -X POST -H "Content-Type: application/json" -d '[1,2,3]' http://127.0.0.1:1323/1
[
  1,
  2,
  3
]

Actual behaviour

curl -X POST -H "Content-Type: application/json" -d '[1,2,3]' http://127.0.0.1:1323/1
"code=400, message=binding element must be a struct, internal=binding element must be a struct"

Steps to reproduce

First build and run the code.
Then use curl to create http requests.
It will returan the arrya in first url but not in second url.

curl -X POST -H "Content-Type: application/json" -d '[1,2,3]' http://127.0.0.1:1323
[
  1,
  2,
  3
]
curl -X POST -H "Content-Type: application/json" -d '[1,2,3]' http://127.0.0.1:1323/1
"code=400, message=binding element must be a struct, internal=binding element must be a struct"

Working code to debug

package main

import (
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.Debug = true

	e.POST("", func(ctx echo.Context) error {
		data := make([]uint, 0)
		if err := ctx.Bind(&data); err != nil {
			return err
		}
		return ctx.JSON(200, data)
	})
	e.POST("/:id", func(ctx echo.Context) error {
		data := make([]uint, 0)
		if err := ctx.Bind(&data); err != nil {
			return err
		}
		return ctx.JSON(200, data)
	})

	e.Logger.Fatal(e.Start(":1323"))
}

Version/commit

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions