简体   繁体   English

如何获取我刚刚在Go中设置的一个HTTP header的字符串值?

[英]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.我有以下令人难以置信的简单代码 Go。

 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:但是当我运行它时,它没有按预期工作,这是 output:

h.Get("my_id") =  

Why can't I print out the value of the header I just set?为什么我刚刚设置的header的值打印不出来?

Here is the live code for you to see yourself: https://play.golang.org/p/L45LzVqd341下面是你自己看的直播代码: https://play.golang.org/p/L45LzVqd341

Header.Get uses http.CanonicalHeaderKey to lookup keys. Header.Get使用http.CanonicalHeaderKey来查找键。 If you use h.Set or put My_id , it will work.如果您使用h.Set或 put My_id ,它将起作用。

This is explained in Header.Get documentation.这在Header.Get中有解释。获取文档。

Yeah the Headers are just a map[string][]string .是的,标题只是一个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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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