Debian Codegraph @

pkg/services/sms/twilio/twilio_sender.go

raw
1 package twilio
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/url"
10 "strings"
11 "time"
12 )
13
14 // HTTPClient defines the interface for making HTTP requests.
15 type HTTPClient interface {
16 Do(req *http.Request) (*http.Response, error)
17 }
18
19 // apiErrorResponse represents an error response from the Twilio REST API.
20 type apiErrorResponse struct {
21 Code int `json:"code"`
22 Message string `json:"message"`
23 Status int `json:"status"`
24 }
25
26 const (
27 apiBaseURL = "https://api.twilio.com/2010-04-01/Accounts"
28 contentType = "application/x-www-form-urlencoded"
29 defaultHTTPTimeout = 10 * time.Second
30 msgServicePrefix = "MG"
31 )
32
33 // DefaultHTTPClient returns a new HTTP client with a default timeout.
34 func DefaultHTTPClient() HTTPClient {
35 return &http.Client{
36 Timeout: defaultHTTPTimeout,
37 }
38 }
39
40 // sendToRecipient sends an SMS message to a single recipient via the Twilio API.
41 func (s *Service) sendToRecipient(config *Config, toNumber, message string) error {
42 body := message
43 if config.Title != "" {
44 body = config.Title + "\n" + message
45 }
46
47 apiURL := fmt.Sprintf("%s/%s/Messages.json", apiBaseURL, config.AccountSID)
48
49 data := url.Values{}
50 data.Set("To", toNumber)
51 data.Set("Body", body)
52
53 // Use MessagingServiceSid if the sender looks like a Messaging Service SID,
54 // otherwise use it as a regular From number.
55 if strings.HasPrefix(config.FromNumber, msgServicePrefix) {
56 data.Set("MessagingServiceSid", config.FromNumber)
57 } else {
58 data.Set("From", config.FromNumber)
59 }
60
61 ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
62 defer cancel()
63
64 req, err := http.NewRequestWithContext(
65 ctx,
66 http.MethodPost,
67 apiURL,
68 strings.NewReader(data.Encode()),
69 )
70 if err != nil {
71 return fmt.Errorf("creating request: %w", err)
72 }
73
74 req.Header.Set("Content-Type", contentType)
75 req.SetBasicAuth(config.AccountSID, config.AuthToken)
76
77 res, err := s.HTTPClient.Do(req)
78 if err != nil {
79 return fmt.Errorf("sending request to Twilio API: %w", err)
80 }
81
82 defer func() { _ = res.Body.Close() }()
83
84 if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices {
85 return parseAPIError(res)
86 }
87
88 return nil
89 }
90
91 // parseAPIError reads the Twilio API error response body and returns a descriptive error.
92 func parseAPIError(res *http.Response) error {
93 respBody, err := io.ReadAll(res.Body)
94 if err != nil {
95 return fmt.Errorf("%w: response status %q (failed to read body)", ErrSendFailed, res.Status)
96 }
97
98 var apiErr apiErrorResponse
99
100 err = json.Unmarshal(respBody, &apiErr)
101 if err == nil && apiErr.Message != "" {
102 return fmt.Errorf("%w: %s (code %d)", ErrSendFailed, apiErr.Message, apiErr.Code)
103 }
104
105 return fmt.Errorf("%w: response status %q", ErrSendFailed, res.Status)
106 }