简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM