github.com/kvattikuti/drone@v0.2.1-0.20140603034306-d400229a327a/pkg/plugin/notify/webhook.go (about)

     1  package notify
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"net/http"
     7  
     8  	"github.com/drone/drone/pkg/model"
     9  )
    10  
    11  type Webhook struct {
    12  	URL     []string `yaml:"urls,omitempty"`
    13  	Success bool     `yaml:"on_success,omitempty"`
    14  	Failure bool     `yaml:"on_failure,omitempty"`
    15  }
    16  
    17  func (w *Webhook) Send(context *Context) error {
    18  	switch {
    19  	case context.Commit.Status == "Success" && w.Success:
    20  		return w.send(context)
    21  	case context.Commit.Status == "Failure" && w.Failure:
    22  		return w.send(context)
    23  	}
    24  
    25  	return nil
    26  }
    27  
    28  // helper function to send HTTP requests
    29  func (w *Webhook) send(context *Context) error {
    30  	// data will get posted in this format
    31  	data := struct {
    32  		Owner  *model.User   `json:"owner"`
    33  		Repo   *model.Repo   `json:"repository"`
    34  		Commit *model.Commit `json:"commit"`
    35  	}{context.User, context.Repo, context.Commit}
    36  
    37  	// data json encoded
    38  	payload, err := json.Marshal(data)
    39  	if err != nil {
    40  		return err
    41  	}
    42  
    43  	// loop through and email recipients
    44  	for _, url := range w.URL {
    45  		go sendJson(url, payload)
    46  	}
    47  	return nil
    48  }
    49  
    50  // helper fuction to sent HTTP Post requests
    51  // with JSON data as the payload.
    52  func sendJson(url string, payload []byte) {
    53  	buf := bytes.NewBuffer(payload)
    54  	resp, err := http.Post(url, "application/json", buf)
    55  	if err != nil {
    56  		return
    57  	}
    58  	resp.Body.Close()
    59  }