2014-09-10 06:19:04 +00:00
|
|
|
package webhook
|
2014-02-07 10:10:01 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
2014-06-12 23:41:04 +00:00
|
|
|
"github.com/drone/drone/shared/model"
|
2014-02-07 10:10:01 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Webhook struct {
|
|
|
|
URL []string `yaml:"urls,omitempty"`
|
2014-09-10 06:19:04 +00:00
|
|
|
Success *bool `yaml:"on_success,omitempty"`
|
|
|
|
Failure *bool `yaml:"on_failure,omitempty"`
|
2014-02-07 10:10:01 +00:00
|
|
|
}
|
|
|
|
|
2014-07-13 02:01:34 +00:00
|
|
|
func (w *Webhook) Send(context *model.Request) error {
|
2014-02-07 10:10:01 +00:00
|
|
|
switch {
|
2014-09-10 06:19:04 +00:00
|
|
|
case context.Commit.Status == model.StatusSuccess && w.Success != nil && *w.Success == true:
|
2014-02-07 10:10:01 +00:00
|
|
|
return w.send(context)
|
2014-09-10 06:19:04 +00:00
|
|
|
case context.Commit.Status == model.StatusFailure && w.Failure != nil && *w.Success == true:
|
2014-02-07 10:10:01 +00:00
|
|
|
return w.send(context)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// helper function to send HTTP requests
|
2014-07-13 02:01:34 +00:00
|
|
|
func (w *Webhook) send(context *model.Request) error {
|
2014-02-07 10:10:01 +00:00
|
|
|
// data will get posted in this format
|
|
|
|
data := struct {
|
2015-01-14 05:57:30 +00:00
|
|
|
From string `json:"from_url"`
|
2014-06-12 23:41:04 +00:00
|
|
|
Owner *model.User `json:"owner"`
|
|
|
|
Repo *model.Repo `json:"repository"`
|
|
|
|
Commit *model.Commit `json:"commit"`
|
2015-01-14 05:57:30 +00:00
|
|
|
}{context.Host, context.User, context.Repo, context.Commit}
|
2014-02-07 10:10:01 +00:00
|
|
|
|
|
|
|
// 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()
|
|
|
|
}
|