Last active
June 6, 2022 06:41
-
-
Save topaztee/f8ec446355b210a39f9a05184843e4f8 to your computer and use it in GitHub Desktop.
send slack message in golang
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 slack | |
import ( | |
"bytes" | |
"encoding/json" | |
"net/http" | |
) | |
func Firehose() Slack { | |
return Slack{ | |
url: "https://hooks.slack.com/****", | |
} | |
} | |
type Payload struct { | |
Text string `json:"text"` | |
} | |
type Slack struct { | |
url string | |
} | |
func (s Slack) Post(payload Payload) error { | |
body, err := json.Marshal(payload) | |
if err != nil { | |
return err | |
} | |
_, err = http.DefaultClient.Post(s.url, "application/json", bytes.NewReader(body)) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
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 slack | |
import ( | |
"encoding/json" | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
"github.com/stretchr/testify/require" | |
) | |
func TestPost(t *testing.T) { | |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
payload := &Payload{} | |
err := json.NewDecoder(r.Body).Decode(payload) | |
require.NoError(t, err) | |
require.Equal(t, "hello world:monkey_face:", payload.Text) | |
w.WriteHeader(http.StatusOK) | |
})) | |
defer ts.Close() | |
service := Slack{ | |
url: ts.URL, | |
} | |
err := service.Post(Payload{ | |
Text: "hello world:monkey_face:", | |
}) | |
require.NoError(t, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment