[Go] Post a message to Slack with chat.postMessage

Created on November 30, 2026

Send a form-encoded HTTP POST to Slack's chat.postMessage endpoint. The form contains the channel ID and message. Set the SLACK_BOT_TOKEN environment variable to a bot token with the chat:write scope, and replace the example channel ID with one the app can post to.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
    "strings"
    "time"
)

func main() {
    token := os.Getenv("SLACK_BOT_TOKEN")
    if token == "" {
        log.Fatal("Set SLACK_BOT_TOKEN")
    }

    form := url.Values{
        "text":    {"Hello World"},
        "channel": {"C0123456789"},
    }
    req, err := http.NewRequest(http.MethodPost,
        "https://slack.com/api/chat.postMessage", strings.NewReader(form.Encode()))
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Authorization", "Bearer "+token)
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    client := &http.Client{Timeout: 15 * time.Second}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        log.Fatal(fmt.Errorf("Slack returned %s", resp.Status))
    }

    var result struct {
        OK    bool   `json:"ok"`
        Error string `json:"error"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        log.Fatal(err)
    }
    if !result.OK {
        log.Fatal(result.Error)
    }
}

url.Values.Encode() encodes the fields for the request body. Slack can report an API error in a successful HTTP response, so the program also checks the JSON ok field.

Reference

Go Slack