无法获取 HTTP 标头

时间:2024-04-05

浏览:350

作者:佚名

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《无法获取 HTTP 标头》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我不明白为什么 func (h header) get(key string) string in package http in file header.go 不能按预期工作。

我想获取标头“soapaction”,无论其大小写如何,但我只得到一个空字符串 ""。直接访问按预期工作。

soapaction1 := r.header.get("soapaction")
soapaction2 := r.header["soapaction"]

fmt.println("soapaction1: ", soapaction1, " , soapaction2:", soapaction2)

// got:      soapaction:              , soapaction2: [mysoapheader]
// expected: soapaction: mysoapheader , soapaction2: [mysoapheader]
// Get gets the first value associated with the given key. If
// there are no values associated with the key, Get returns "".
// It is case insensitive; textproto.CanonicalMIMEHeaderKey is
// used to canonicalize the provided key. To use non-canonical keys,
// access the map directly.
func (h Header) Get(key string) string {
    return textproto.MIMEHeader(h).Get(key)
}


解决方案


来自 the documentation(已添加重点):

get 获取与给定键关联的第一个值。如果没有与该键关联的值,则 get 返回“”。不区分大小写; textproto.canonicalmimeheaderkey 用于规范化提供的密钥。要使用非规范密钥,请直接访问地图。

您的标头 soapaction 不规范,因此您有两个选择:

  1. 使用规范版本 (soapaction)
  2. 按照文档说明以及您所做的那样,使用直接访问。

http.header.get 方法依赖于字符串转换来获取给定字符串的值。

该转换由 textproto 包实现

https://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey

你可以自己尝试一下:

package main

import (
    "fmt"
    "net/textproto"
)

func main() {
    fmt.Println(textproto.CanonicalMIMEHeaderKey("SOAPAction"))
}

它打印:soapaction

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页