Created
October 7, 2019 12:48
-
-
Save danesparza/8eeda3a0d50deb9ca833faabc73dd9d0 to your computer and use it in GitHub Desktop.
Send a Slack notification to a channel using an incoming webhook on an app
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 ( | |
"bytes" | |
"encoding/json" | |
"errors" | |
"log" | |
"net/http" | |
"time" | |
) | |
type SlackRequestBody struct { | |
Text string `json:"text"` | |
} | |
func main() { | |
webhookURL := "https://hooks.slack.com/services/X1234" | |
err := SendSlackNotification(webhookURL, "Test Message from golangcode.com") | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
// SendSlackNotification will post to an 'Incoming Webook' url setup in Slack Apps. It accepts | |
// some text and the slack channel is saved within Slack. | |
func SendSlackNotification(webhookURL string, msg string) error { | |
slackBody, _ := json.Marshal(SlackRequestBody{Text: msg}) | |
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) | |
if err != nil { | |
return err | |
} | |
buf := new(bytes.Buffer) | |
buf.ReadFrom(resp.Body) | |
if buf.String() != "ok" { | |
return errors.New("Non-ok response returned from Slack") | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken shamelessly from https://golangcode.com/send-slack-messages-without-a-library/