5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

go言語でSlackのWebhookをやろうとして苦労したので備忘録

Last updated at Posted at 2021-03-23

環境

  • go 1.15
  • slack 2021/03/22時点

goの url.QueryEscape は空白( )をプラス(+)に変換する

URLエンコード的にはプラス(+)でも問題ないが、 %20 に変換したい場合は以下のようにする。

str = regexp.MustCompile(([^%])(+)).ReplaceAllString(str, "$1%20")

Slackのサンプルには下記コマンドが提供されているがダブルクォートのエスケープが必要なのか分からない。。

curl -X POST --data-urlencode "payload={\"channel\": \"#any_channel\", \"username\": \"webhookbot\", \"text\": \"This is posted to #any_channel and comes from a bot named webhookbot.\", \"icon_emoji\": \":ghost:\"}" https://hooks.slack.com/services/T5L640XXX/B01S6CZXXXX/XXXXXXXXXXXXXXXXXXXXXXXX

これは単に curl--data-urlencode オプションやシェルのダブルクォートの話。
この文字列の指定であれば、Value(イコール(=)の右側)の部分のみURLエンコードされるらしい。
ダブルクォートの中の変数や式は展開されるのでエスケープが必要らしい。
以下が詳しい。
https://qiita.com/tkms0106/items/4272ce690217c259739c
https://qiita.com/aosho235/items/d89bb027db0c5662d8c5

goだと以下のようなコードでOK。

str := url.QueryEscape(string(body))
str := "payload=" + regexp.MustCompile(`([^%])(\+)`).ReplaceAllString(str, "$1%20")

リクエストのContent-Typeは application/x-www-form-urlencoded

まあ当たり前といえば当たり前。。
goのコードは以下のような感じ。

req, err := http.NewRequest("POST", baseURL, bytes.NewBuffer([]byte(str)))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

リクエストのUser-Agentは必須

User-Agentヘッダーが無い場合は、400 Bad Request になりボディに invalid_payload が返る。
User-Agentの値は何でもよい。
goのコードは以下のような感じ。

req, err := http.NewRequest("POST", baseURL, bytes.NewBuffer([]byte(str)))
req.Header.Set("User-Agent", "hogehoe client")
5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?