44 lines
1003 B
Go
44 lines
1003 B
Go
package notify
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
// Webhook delivers notifications as a JSON POST of the Event to a
|
|
// project-configured URL. Config is {"url": "..."}. secret is currently
|
|
// unused (reserved for future request signing) and is never logged.
|
|
type Webhook struct {
|
|
HTTP *http.Client
|
|
}
|
|
|
|
func (w *Webhook) Send(ctx context.Context, cfg json.RawMessage, secret string, ev Event) error {
|
|
var c struct {
|
|
URL string `json:"url"`
|
|
}
|
|
if err := json.Unmarshal(cfg, &c); err != nil {
|
|
return err
|
|
}
|
|
body, err := json.Marshal(ev)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := w.HTTP.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return fmt.Errorf("webhook: status %d", resp.StatusCode)
|
|
}
|
|
return nil
|
|
}
|