Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
post slack with apex-go
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/apex/go-apex"
)
type inMessage struct {
Message string `json:"message"`
}
type slackMessage struct {
Text string `json:"text"`
}
func main() {
apex.HandleFunc(func(event json.RawMessage, ctx *apex.Context) (interface{}, error) {
inJson := inMessage{}
err := json.Unmarshal(event, &inJson)
if err != nil {
return nil, err
}
slackUrl := os.Getenv("SLACK_WEBHOOK_URL")
if slackUrl == "" {
return nil, errors.New("SLACK_WEBHOOK_URL is not set.")
}
if inJson.Message == "" {
println("get request but no message in message.")
return "OK", nil
}
m := slackMessage{
Text: inJson.Message,
}
pJson, err := json.Marshal(m)
if err != nil {
return nil, err
}
resp, err := http.Post(slackUrl, "application/json", bytes.NewBuffer(pJson))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("slack response %d and error when reading response body", resp.StatusCode)
}
return nil, fmt.Errorf("slack response %d %s", resp.StatusCode, string(body))
}
return "OK", nil
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment