File: hipchat.go

package info (click to toggle)
golang-github-cloudflare-redoctober 0.0~git20161017.0.78e9720-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 584 kB
  • ctags: 560
  • sloc: sh: 65; makefile: 7
file content (67 lines) | stat: -rw-r--r-- 1,336 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package hipchat

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strconv"
)

const (
	RedBackground    = "red"
	YellowBackground = "yellow"
	GreenBackground  = "green"
	GrayBackground   = "gray"
	RandomBackground = "random"
	PurpleBackground = "purple"
)

type HipchatClient struct {
	RoomId int
	ApiKey string
	HcHost string
	RoHost string
}

func NewClient() *HipchatClient {
	return &HipchatClient{}
}
func (h *HipchatClient) Notify(msg, color string) error {
	if h.ApiKey == "" {
		return errors.New("ApiKey unset")
	}
	msgBody := map[string]interface{}{
		"message": msg,
		"notify":  "true",
		"color":   color,
	}

	body, err := json.Marshal(msgBody)
	if err != nil {
		return err
	}
	roomId := url.QueryEscape(strconv.Itoa(h.RoomId))
	hipchatUrl := fmt.Sprintf("https://%s/v2/room/%s/message?auth_token=%s", h.HcHost, roomId, h.ApiKey)
	req, err := http.NewRequest("POST", hipchatUrl, bytes.NewReader(body))

	req.Header.Add("Content-Type", "application/json")

	Client := http.Client{}
	resp, err := Client.Do(req)
	if err != nil {
		log.Printf("Could not post to hipchat for the reason %s", err.Error())
		return err
	}

	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("Could not post to hipchat for the reason %s", err.Error())
		return err
	}
	return nil
}