| 1 | package hipchat |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io/ioutil" |
| 9 | "log" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "strconv" |
| 13 | ) |
| 14 | |
| 15 | const ( |
| 16 | RedBackground = "red" |
| 17 | YellowBackground = "yellow" |
| 18 | GreenBackground = "green" |
| 19 | GrayBackground = "gray" |
| 20 | RandomBackground = "random" |
| 21 | PurpleBackground = "purple" |
| 22 | ) |
| 23 | |
| 24 | type HipchatClient struct { |
| 25 | RoomId int |
| 26 | ApiKey string |
| 27 | HcHost string |
| 28 | RoHost string |
| 29 | } |
| 30 | |
| 31 | func NewClient() *HipchatClient { |
| 32 | return &HipchatClient{} |
| 33 | } |
| 34 | func (h *HipchatClient) Notify(msg, color string) error { |
| 35 | if h.ApiKey == "" { |
| 36 | return errors.New("ApiKey unset") |
| 37 | } |
| 38 | msgBody := map[string]interface{}{ |
| 39 | "message": msg, |
| 40 | "notify": "true", |
| 41 | "color": color, |
| 42 | } |
| 43 | |
| 44 | body, err := json.Marshal(msgBody) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | roomId := url.QueryEscape(strconv.Itoa(h.RoomId)) |
| 49 | hipchatUrl := fmt.Sprintf("https://%s/v2/room/%s/message?auth_token=%s", h.HcHost, roomId, h.ApiKey) |
| 50 | req, err := http.NewRequest("POST", hipchatUrl, bytes.NewReader(body)) |
| 51 | |
| 52 | req.Header.Add("Content-Type", "application/json") |
| 53 | |
| 54 | Client := http.Client{} |
| 55 | resp, err := Client.Do(req) |
| 56 | if err != nil { |
| 57 | log.Printf("Could not post to hipchat for the reason %s", err.Error()) |
| 58 | return err |
| 59 | } |
| 60 | |
| 61 | _, err = ioutil.ReadAll(resp.Body) |
| 62 | if err != nil { |
| 63 | log.Printf("Could not post to hipchat for the reason %s", err.Error()) |
| 64 | return err |
| 65 | } |
| 66 | return nil |
| 67 | } |