| 188 | } |
| 189 | |
| 190 | func postMessage(context webhook.Context) error { |
| 191 | post := BuildMessage(context) |
| 192 | body, err := marshal(post) |
| 193 | if err != nil { |
| 194 | return errors.Wrap(err, "failed to marshal Google Chat webhook POST request") |
| 195 | } |
| 196 | req, err := http.NewRequest(http.MethodPost, context.URL, bytes.NewBuffer(body)) |
| 197 | if err != nil { |
| 198 | return errors.New("failed to construct Google Chat webhook POST request") |
| 199 | } |
| 200 | |
| 201 | req.Header.Set("Content-Type", "application/json; charset=UTF-8") |
| 202 | client := &http.Client{ |
| 203 | Timeout: webhook.Timeout, |
| 204 | } |
| 205 | resp, err := client.Do(req) |
| 206 | if err != nil { |
| 207 | return errors.New("failed to POST Google Chat webhook") |
| 208 | } |
| 209 | defer resp.Body.Close() |
| 210 | |
| 211 | b, err := io.ReadAll(resp.Body) |
| 212 | if err != nil { |
| 213 | return errors.New("failed to read Google Chat webhook response") |
| 214 | } |
| 215 | if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { |
| 216 | return errors.Errorf("failed to POST Google Chat webhook, status code: %d, response body: %s", resp.StatusCode, b) |
| 217 | } |
| 218 | |
| 219 | return nil |
| 220 | } |
| 221 | |
| 222 | func marshal(post MessagePayload) ([]byte, error) { |
| 223 | var body bytes.Buffer |