How do I call Slack APIs with rate limits in Go?

In Go, when working with Slack APIs, it is crucial to manage rate limits to avoid being blocked by the API. Slack enforces rate limits on their endpoints, and handling these limits effectively is essential for building reliable integrations. Below is an example of how to call Slack APIs with rate limits implemented in Go.

package main import ( "fmt" "net/http" "time" ) const ( slackAPIUrl = "https://slack.com/api/" token = "YOUR_SLACK_BOT_TOKEN" ) func callSlackAPI(endpoint string, params map[string]string) (*http.Response, error) { // Build the request URL req, err := http.NewRequest("GET", slackAPIUrl+endpoint, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+token) // Add query parameters q := req.URL.Query() for key, value := range params { q.Add(key, value) } req.URL.RawQuery = q.Encode() // Make the request client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } // Check for rate limits if resp.StatusCode == 429 { reset := resp.Header.Get("Retry-After") if reset != "" { waitTime, _ := time.ParseDuration(reset + "s") time.Sleep(waitTime) } return callSlackAPI(endpoint, params) // Retry the request } return resp, nil } func main() { params := map[string]string{ "channel": "YOUR_CHANNEL_ID", "text": "Hello, Slack!", } resp, err := callSlackAPI("chat.postMessage", params) if err != nil { fmt.Println("Error calling Slack API:", err) return } defer resp.Body.Close() fmt.Println("Response Status:", resp.Status) }

keywords: Slack API Go rate limits integration