cannot get request header

6.6k views Asked by At

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: */*
2

There are 2 answers

0
Steffen Ullrich On BEST ANSWER
        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 {
0
Carlo Nyte On

Since I can't edit @Steffen to show the complete code I'll add it here:

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"))
}