Debian Codegraph @

pkg/services/chat/googlechat/googlechat.go

raw symbols SCIP
1 package googlechat
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "net/http"
10 "net/url"
11 "time"
12
13 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
14 "github.com/nicholas-fedor/shoutrrr/pkg/types"
15 )
16
17 // Service implements a Google Chat notification service.
18 type Service struct {
19 standard.Standard
20
21 Config *Config
22 httpClient types.HTTPClient
23 }
24
25 const defaultHTTPTimeout = 10 * time.Second
26
27 // ErrUnexpectedStatus indicates an unexpected HTTP status code from the Google Chat API.
28 var ErrUnexpectedStatus = errors.New("google chat api returned unexpected http status code")
29
30 // GetID returns the identifier for this service.
31 func (s *Service) GetID() string {
32 return Scheme
33 }
34
35 // Initialize configures the service with a URL and logger.
36 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
37 s.SetLogger(logger)
38
39 s.Config = &Config{}
40
41 if s.httpClient == nil {
42 s.httpClient = &http.Client{Timeout: defaultHTTPTimeout}
43 }
44
45 return s.Config.SetURL(serviceURL)
46 }
47
48 // Send delivers a notification message to Google Chat.
49 func (s *Service) Send(message string, _ *types.Params) error {
50 config := s.Config
51
52 jsonBody, err := json.Marshal(JSON{Text: message})
53 if err != nil {
54 return fmt.Errorf("marshaling message to JSON: %w", err)
55 }
56
57 postURL := getAPIURL(config)
58 jsonBuffer := bytes.NewBuffer(jsonBody)
59
60 req, err := http.NewRequestWithContext(
61 context.Background(),
62 http.MethodPost,
63 postURL.String(),
64 jsonBuffer,
65 )
66 if err != nil {
67 return fmt.Errorf("creating HTTP request: %w", err)
68 }
69
70 req.Header.Set("Content-Type", "application/json")
71
72 resp, err := s.httpClient.Do(req)
73 if err != nil {
74 return fmt.Errorf("sending notification to Google Chat: %w", err)
75 }
76
77 defer func() { _ = resp.Body.Close() }()
78
79 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
80 return fmt.Errorf("%w: %d", ErrUnexpectedStatus, resp.StatusCode)
81 }
82
83 return nil
84 }
85
86 // SetHTTPClient sets a custom HTTP client for the service.
87 func (s *Service) SetHTTPClient(client types.HTTPClient) {
88 s.httpClient = client
89 }
90
91 // getAPIURL constructs the service URL for Google Chat notifications.
92 func getAPIURL(config *Config) *url.URL {
93 query := url.Values{}
94 query.Set("key", config.Key)
95 query.Set("token", config.Token)
96
97 return &url.URL{
98 Path: config.Path,
99 Host: config.Host,
100 Scheme: "https",
101 RawQuery: query.Encode(),
102 }
103 }