我正在使用Slack Web API将消息发布到Go中的 channel 。我正在尝试在文本字段中支持多行消息。根据文档,仅添加\n应该可以,但是不起作用。发布时,\n出现在文本中,没有换行符。
这是我正在使用的代码:
func PostMessage(token, channelName, userName, text string) error {
uv := url.Values{}
uv.Add("token", token)
uv.Add("channel", channelName)
uv.Add("username", userName)
uv.Add("text", text)
resp, err := http.PostForm("https://slack.com/api/chat.postMessage", uv)
if err != nil {
return err
}
return nil
}
func main() {
if err := PostMessage("xxxx", "#test-channel", "API", "This should be the first line\nThis should be the second line"); err != nil {
panic(err)
}
}
最佳答案
我发现了问题。我最初发布的示例实际上可以按预期工作。我简化了原始代码,这是一个命令行应用程序,其中的文本是作为CLI标志传递的参数,因此看起来有点像这样:
cliapp --text="one\ntwo"
保留该标志值的变量实际上并未转义字符,因此实际上是:
"one\\ntwo"
我使用简单的字符串替换来修复值:
text = strings.Replace(text, "\\n", "\n", -1)
关于go - Slack API使用\n作为新行在chat.postMessage(golang)中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37195607/