http - golang发送请求时偶尔报错400
问题描述
这是我现在拥有的:
func (client Client) PressButton(i int, k int, msg Message) error {
if client.Token == "" {
return fmt.Errorf("no token")
}
i--
k--
url := "https://discord.com/api/v9/interactions"
time.Sleep(2 * time.Second)
data := map[string]interface{}{"component_type": msg.Components[i].Buttons[k].Type, "custom_id": msg.Components[i].Buttons[k].CustomID, "hash": msg.Components[i].Buttons[k].Hash}
values := map[string]interface{}{"application_id": "270904126974590976", "channel_id": msg.ChannelID, "type": "3", "data": data, "guild_id": msg.GuildID, "message_flags": 0, "message_id": msg.ID,}
json_data, err := json.Marshal(values)
if err != nil {
return fmt.Errorf("error while encoding button click as json: %v", err)
}
req, err := http.NewRequest("POST", url, strings.NewReader(string(json_data)))
if err != nil {
return fmt.Errorf("error while creating http request: %v", err)
}
req.Header.Set("authorization", client.Token)
req.Header.Set("Content-Type", "application/json")
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("error while sending http request: %v", err)
}
if resp.StatusCode != 204 {
switch resp.StatusCode {
case http.StatusUnauthorized:
return ErrUnauthorized
case http.StatusForbidden:
return ErrForbidden
case http.StatusNotFound:
return ErrNotFound
case http.StatusTooManyRequests:
return ErrTooManyRequests
case http.StatusInternalServerError:
return ErrIntervalServer
default:
return fmt.Errorf("unexpected status code while clicking button: %v", resp.StatusCode)
}
}
return nil
}
这在 90% 的情况下都能完美运行。但有时我会收到 400 错误。我查了一下,我尝试了所有推荐的解决方案,我已经确认有效负载和 URL 是绝对正确的,而且如果它们不是,它在大多数情况下都不会工作。我还尝试更改标题等。
这是发送的示例有效负载(编组之前):
map[application_id:12345 channel_id:872747211551801384 data:map[component_type:2 custom_id:c34117ee-a332-4d7c-888f-47081e40092f:0 hash:]
(更改了应用程序ID)
响应状态为 400,这是响应正文:
{"code": 50035, "errors": {"data": {"_errors": [{"code": "COMPONENT_VALIDATION_FAILED", "message": "Component validation failed"}]}}, "message": "Invalid Form Body"}
我已经完全搜索了不和谐的互联网和编码服务器,以了解为什么会发生这种情况。哈希现在总是一个空字段,之前它曾经对我的用例有一个值。我只是把它留在里面,所以它更笼统。
解决方案
推荐阅读
- azure-devops - 如何比较 VSTS 中的两个非顺序拉取请求更新?
- android - Android anjlab 应用内计费 - 收费
- php - 通过php在bigquery中执行插入操作
- asp.net - 解码请求中发送的 __VIEWSTATE
- javascript - 在Angularjs运行块中等待异步javascript
- javascript - 页面加载时的 HtmlUnit JavaScript 问题 - 找不到函数
- regex - [Regex]::Replace() 和 -replace 有什么区别?
- symfony-3.4 - 如何在我的项目中独立使用事件命令 Symfony?
- node.js - 调试我的打字稿文件时出错:-> 附加调试器。等待调试器断开连接
- ruby-on-rails - 如何检查 ruby on rails 中的表单完整性?