Sending a Slack Message (without a library)

· 275 words · 2 minutes read

Programs often need to notify us of events and using services like Slack, Hipchat (or even email) make this convenient for us. This code snippet is a way of sending a message to Slack via an Incoming Webhook - you can set these up in the Slack Apps area. All you need is to set the incoming webhook url and change the text to be anything you want.

It does include a timeout (of 10 seconds) if something happens to Slack response times for any reason. It also checks that the response doesn’t return an error.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main

import (
    "bytes"
    "encoding/json"
    "errors"
    "log"
    "net/http"
    "time"
)

type SlackRequestBody struct {
    Text string `json:"text"`
}

func main() {
    webhookUrl := "/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
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!