cannot get request header

Issue

I tried to print the request header using the echo framework, but it seems the echo framework does not load the header into the context.request.Header fields. Is this a bug for the echo framework?

Here is the main function, and context.Request() is a type of *http.Request,

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

    server.GET("/", func(context echo.Context) error {

        for key, values := range context.Request().Header {
            fmt.Println(key)
            for value := range values {
                fmt.Println(value)
            }
        }
        return nil
    })

    server.Logger.Fatal(server.Start(":12312"))
}

I use curl curl -vvv "http://127.0.0.1:12312/" to test the server, but the server only print

User-Agent
0
Accept
0

but actually, the curl gives the following as header info

> Host: 127.0.0.1:12312
> User-Agent: curl/7.64.1
> Accept: */*

Solution

        for value := range values {

Using range on a list returns index, value. You only ask for the index, which is 0 in all cases. To get the actual values use

        for _,value := range values {

Answered By – Steffen Ullrich

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.