1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-12-24 10:07:21 +02:00
woodpecker/plugin/notify/webhook/webhook.go

59 lines
1.3 KiB
Go
Raw Normal View History

package webhook
2014-02-07 13:10:01 +03:00
import (
"bytes"
"encoding/json"
"net/http"
"github.com/drone/drone/shared/model"
2014-02-07 13:10:01 +03:00
)
type Webhook struct {
URL []string `yaml:"urls,omitempty"`
Success *bool `yaml:"on_success,omitempty"`
Failure *bool `yaml:"on_failure,omitempty"`
2014-02-07 13:10:01 +03:00
}
func (w *Webhook) Send(context *model.Request) error {
2014-02-07 13:10:01 +03:00
switch {
case context.Commit.Status == model.StatusSuccess && w.Success != nil && *w.Success == true:
2014-02-07 13:10:01 +03:00
return w.send(context)
case context.Commit.Status == model.StatusFailure && w.Failure != nil && *w.Success == true:
2014-02-07 13:10:01 +03:00
return w.send(context)
}
return nil
}
// helper function to send HTTP requests
func (w *Webhook) send(context *model.Request) error {
2014-02-07 13:10:01 +03:00
// data will get posted in this format
data := struct {
Owner *model.User `json:"owner"`
Repo *model.Repo `json:"repository"`
Commit *model.Commit `json:"commit"`
2014-02-07 13:10:01 +03:00
}{context.User, context.Repo, context.Commit}
// data json encoded
payload, err := json.Marshal(data)
if err != nil {
return err
}
for _, url := range w.URL {
go sendJson(url, payload)
}
return nil
}
// helper fuction to sent HTTP Post requests
// with JSON data as the payload.
func sendJson(url string, payload []byte) {
buf := bytes.NewBuffer(payload)
resp, err := http.Post(url, "application/json", buf)
if err != nil {
return
}
resp.Body.Close()
}