/
hangouts.go
72 lines (55 loc) · 1.5 KB
/
hangouts.go
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
68
69
70
71
72
package hangouts
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"github.com/containrrr/shoutrrr/pkg/services/standard"
"github.com/containrrr/shoutrrr/pkg/types"
)
// Service providing Hangouts Chat as a notification service.
type Service struct {
standard.Standard
config *Config
}
// Initialize loads ServiceConfig from configURL and sets logger for this Service.
func (service *Service) Initialize(configURL *url.URL, logger *log.Logger) error {
service.Logger.SetLogger(logger)
service.config = &Config{}
err := service.config.SetURL(configURL)
return err
}
// Send a notification message to Hangouts Chat.
func (service *Service) Send(message string, _ *types.Params) error {
config := service.config
jsonBody, err := json.Marshal(JSON{
Text: message,
})
if err != nil {
return err
}
postURL := getAPIURL(config)
jsonBuffer := bytes.NewBuffer(jsonBody)
resp, err := http.Post(postURL.String(), "application/json", jsonBuffer)
if err != nil {
return fmt.Errorf("failed to send notification to Hangouts Chat: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("Hangouts Chat API notification returned %d HTTP status code", resp.StatusCode)
}
return nil
}
func getAPIURL(config *Config) *url.URL {
query := url.Values{}
query.Set("key", config.Key)
query.Set("token", config.Token)
return &url.URL{
Path: config.Path,
Host: config.Host,
Scheme: "https",
RawQuery: query.Encode(),
}
}