Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created October 7, 2019 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danesparza/8eeda3a0d50deb9ca833faabc73dd9d0 to your computer and use it in GitHub Desktop.
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
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
}
@danesparza
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment