我是golang的新手,我正在编写一个脚本,使用传入的Webhook将消息发送到松弛状态。
slackBody, _ := json.Marshal(SlackRequestBody{Text: msg, EventName: "xxx", AccountId: "xxx",
EventTime: "xxxxx", UserName: "xxxx", yyy: "xx", Status: "xx"})
fmt.Println(string(slackBody))
//test := ioutil.ReadAll(bytes.NewBuffer(slackBody))
req, err := http.NewRequest(http.MethodPost, webhookUrl, bytes.NewBuffer(slackBody))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
此帖子请求仅包含“ req”请求中的几个单词。您能帮我解决问题吗?
bytes.NewBuffer()
在这里没有任何问题。从松弛的角度来看,它仅识别“文本”字段提供的消息。您需要重新设计SlackRequestBody
结构。当您使用Webhook API发送消息时,您的请求主体应遵循slack
给出的结构格式。
POST https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
Content-type: application/json
{
"text": ...
"blocks": ...
"attachments": ...
"thread_ts": ...
"mrkdwn": ...
... ... ...
}
因此,您的SlackRequestBody
结构应类似于:
package main
import (
"encoding/json"
"fmt"
"time"
)
type SlackRequestBody struct {
Text string `json:"text"`
Blocks []Block `json:"blocks,omitempty"`
ThreadTimestamp string `json:"thread_ts,omitempty"`
Mrkdwn bool `json:"mrkdwn,omitempty"`
}
type Block struct {
BlockID string `json:"block_id,omitempty"`
Type string `json:"type"`
Text Text `json:"text"`
}
type Text struct {
Type string `json:"type"`
Text string `json:"text"`
}
func main() {
var payload = &SlackRequestBody{
Text: "Your message",
Blocks: []Block{
{
Type: "section",
Text: Text{
Type: "plain_text",
Text: "User Name: XXXX",
},
BlockID: "username",
},
{
Type: "section",
Text: Text{
Type: "plain_text",
Text: "Event Time: " + time.Now().String(),
},
BlockID: "eventTime",
},
},
}
data, err := json.Marshal(payload)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
{ "text":"Your message", "blocks":[ { "block_id":"username", "type":"section", "text":{ "type":"plain_text", "text":"User Name: XXXX" } }, { "block_id":"eventTime", "type":"section", "text":{ "type":"plain_text", "text":"Event Time: 2020-03-29 14:11:33.533827881 +0600 +06 m=+0.000078203" } } ] }
我建议您使用松弛的官方go client。它将提供更多的灵活性。编码愉快。