Created
July 2, 2017 13:51
-
-
Save reiki4040/afe3bd4317992b4748b0983f51058fae to your computer and use it in GitHub Desktop.
post slack with apex-go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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