Saqib Ali
Saqib Ali

Reputation: 12575

How to get the string value of an HTTP header that I just set in Go?

I have the following mind-blowingly simple Go code.

 package main
 
 import (
    "fmt"
    "net/http"
 )
 func main() {
    h := http.Header{
        "my_id": []string{"XYZ"},
    }
     fmt.Println("h.Get(\"my_id\") = ", h.Get("my_id"))
 }

But when I run it it doesn't work as expected, Here is the output:

h.Get("my_id") =  

Why can't I print out the value of the header I just set?

Here is the live code for you to see yourself: https://play.golang.org/p/L45LzVqd341

Upvotes: 0

Views: 1164

Answers (2)

RuNpiXelruN
RuNpiXelruN

Reputation: 1920

Yeah the Headers are just a map[string][]string. So you can always get access to them by simply

if myID, ok := h["my_id"]; ok {
    fmt.Println("myID", myID)
} else {
    fmt.Println("my_id header not found")
}

Upvotes: 0

Burak Serdar
Burak Serdar

Reputation: 51577

Header.Get uses http.CanonicalHeaderKey to lookup keys. If you use h.Set or put My_id, it will work.

This is explained in Header.Get documentation.

Upvotes: 4

Related Questions