Skip to content

Bind Fails with Transfer-Encoding: chunked #2716

Closed
@178inaba

Description

@178inaba

Issue Description

Bind fails when Transfer-Encoding: chunked is used.

Working code to debug

Server

package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"

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

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

func main() {
	e := echo.New()
	e.POST("/", func(c echo.Context) error {
		req := c.Request()

		fmt.Println("----------")
		fmt.Println("ContentLength:", req.ContentLength)
		fmt.Println("TransferEncoding:", req.TransferEncoding)
		fmt.Println("----------")

		reqDump, err := httputil.DumpRequest(req, true)
		if err != nil {
			return err
		}
		fmt.Println(string(reqDump))

		var u User
		if err := c.Bind(&u); err != nil {
			return err
		}

		return c.JSON(http.StatusOK, u)
	})

	e.Logger.Fatal(e.Start(":1323"))
}
Log
----------
ContentLength: -1
TransferEncoding: [chunked]
----------
POST / HTTP/1.1
Host: localhost:1323
Transfer-Encoding: chunked
Accept-Encoding: gzip
Content-Type: application/json
User-Agent: Go-http-client/1.1

28
{"name":"foo","email":"[email protected]"}
0

Client

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httputil"
)

func main() {
	req, err := http.NewRequest("POST", "http://localhost:1323", bytes.NewBufferString(`{"name":"foo","email":"[email protected]"}`))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.ContentLength = 0

	reqDump, err := httputil.DumpRequest(req, true)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(reqDump))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	b, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("----------")
	fmt.Println(string(b))
}
Log
POST / HTTP/1.1
Host: localhost:1323
Content-Type: application/json

{"name":"foo","email":"[email protected]"}
----------
{"name":"","email":""}

Version/commit

v4.13.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions