123

golang报错:net/http: invalid header field value "Basic ...

 5 years ago
source link: https://studygolang.com/articles/19665?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

原文地址: golang报错:net/http: invalid header field value "Basic

昨天被这个问题困扰了一天,今天终于找到问题了。

先说一下我这里的流程:

1.从本地文件中读取一个 base64加密过的字符串。然后添加到header上。

auth := getAuth()
//auth 为 Basic XXXXXX  
req.Header.Add("authorization", auth)

但是当执行 client.Do(req)时,会报错:如下图

yAbMjqV.png!web

经过一番"排查",发现当从文件读取字符串时,字符串往往后面会附带一个空行。也就是报错信息后面那些\x00\x00\x00\x00出现的原因了。

解决方法:

str, err := base64.StdEncoding.DecodeString(dataStr)
realStr :=strings.TrimSpace(string(str))
str = []byte(realStr)
dataStr = base64.StdEncoding.EncodeToString(str)

因为我的原信息时base64的所以我这里需要先base64decode, 然后去空行,然后再base64endoe。

如果你的原信息本身就是字符串,可以尝试直接去空行。

然后,问题解决~

完。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK