Last active
July 31, 2017 06:31
-
-
Save isann/a39a4c207d1f1a2f9b617b3e46283b55 to your computer and use it in GitHub Desktop.
レガシーじゃない Slack API のたたきかた ref: http://qiita.com/isann_tech/items/d6574350d3b623fdc1f8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"strings" | |
"net/http" | |
"net/url" | |
) | |
/* | |
Slack にメッセージを送信します。 | |
*/ | |
func sendSlack(title, msg string) bool { | |
requestUrl := "https://slack.com/api/chat.postMessage" | |
postData := map[string]string{ | |
"token": "xoxp-XXX-XXX-XXXXXX-XXXXXXXXX", | |
"channel": "err_replication_bot", | |
"text": title + "\n```" + msg + "```", | |
} | |
_, err := requestHttp(requestUrl, "post", nil, postData, nil, "") | |
if err != nil { | |
return false | |
} | |
return true | |
} | |
func requestHttp(requestUrl string, method string, getParam map[string]string, postParam map[string]string, cookie *http.Cookie, userAgent string) (*http.Response, error) { | |
var req *http.Request | |
var err error | |
if strings.ToLower(method) == "post" { | |
values := url.Values{} | |
if postParam != nil { | |
for key, val := range postParam { | |
values.Add(key, val) | |
} | |
} | |
req, err = http.NewRequest("POST", requestUrl, strings.NewReader(values.Encode())) | |
if err != nil { | |
return nil, err | |
} | |
} else if strings.ToLower(method) == "get" { | |
req, err = http.NewRequest("GET", requestUrl, nil) | |
if err != nil { | |
return nil, err | |
} | |
} | |
// GET parameter | |
if getParam != nil { | |
values2 := url.Values{} | |
for key, val := range getParam { | |
values2.Add(key, val) | |
} | |
req.URL.RawQuery = values2.Encode() | |
} | |
// Request Header | |
if strings.ToLower(method) == "post" { | |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") | |
} | |
if userAgent != "" { | |
req.Header.Add("User-Agent", userAgent) | |
} else { | |
req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MAFSJS; rv:11.0) like Gecko") | |
} | |
if cookie != nil { | |
req.AddCookie(cookie) | |
} | |
// 自動リダイレクトのオフ | |
client := http.Client{ | |
// Go HTTP Client NOT Follow Redirects Automatically. | |
CheckRedirect: func(req *http.Request, via []*http.Request) error { | |
return http.ErrUseLastResponse | |
}, | |
} | |
return client.Do(req) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment