Home > front end >  Golang - Binding Headers in echo api
Golang - Binding Headers in echo api

Time:07-06

Golang - Binding Headers in echo api

I'm trying to bind headers to struct. So far I did the same as in documentation here but it looks like doesn't work at all. I checked in debugger incoming request and it has proper header name and value but echo doesn't bind it.

Here is my api:

package main

import (
    "net/http"

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

type User struct {
    ID string `header:"Id"`
}

func handler(c echo.Context) error {
    request := new(User)

    if err := c.Bind(request); err != nil {
        return c.String(http.StatusBadRequest, err.Error())
    }

    return c.String(http.StatusOK, "rankView")
}

func main() {
    api := echo.New()

    api.POST("product/rank/view", handler)

    api.Start(":3000")
}

and my request

curl -X POST "http://localhost:3000/product/rank/view" \
     -H "accept: application/json" \
     -H "Id: test" \
     -H "Content-Type: application/x-www-form-urlencoded" -d "productId=123132"

CodePudding user response:

See this answer.

Tried this code and it works:

package main

import (
        "fmt"
        "github.com/labstack/echo/v4"
        "net/http"
)

type User struct {
        ID string `header:"Id"`
}

func handler(c echo.Context) error {
        request := new(User)
        binder := &echo.DefaultBinder{}

        binder.BindHeaders(c, request)
        fmt.Printf("% v\n", request)

        return c.String(http.StatusOK, "rankView")
}

func main() {
        api := echo.New()
        api.POST("product/rank/view", handler)
        api.Start(":3000")
}
  • Related