Debian Codegraph @

pkg/services/push/gotify/gotify_send.go

raw
1 package gotify
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10
11 "github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient"
12 )
13
14 // Sender handles HTTP request execution and response processing.
15 type Sender interface {
16 SendRequest(client *http.Client, url string, request *MessageRequest, headers http.Header) error
17 }
18
19 // DefaultSender provides the default implementation of Sender.
20 type DefaultSender struct{}
21
22 // SendRequest handles the HTTP request.
23 // This function executes the actual HTTP POST request to the Gotify API endpoint,
24 // handling both successful responses and error conditions with appropriate error wrapping.
25 // Parameters:
26 // - client: HTTP client to use for the request
27 // - url: The complete API endpoint URL to send the request to
28 // - request: The JSON payload to send in the request body
29 // - headers: Optional headers to set on the request
30 //
31 // Returns: error if the request fails or server returns an error, nil on success.
32 func (s *DefaultSender) SendRequest(
33 client *http.Client,
34 url string,
35 request *MessageRequest,
36 headers http.Header,
37 ) error {
38 // Prepare response structure to capture API response
39 response := &messageResponse{}
40
41 var err error
42
43 if len(headers) == 0 {
44 // Use JSON client for standard requests - this will handle error extraction
45 jsonClient := jsonclient.NewWithHTTPClient(client)
46
47 err = jsonClient.Post(url, request, response)
48 if err != nil {
49 // Try to extract structured error
50 errorRes := &responseError{}
51 if jsonClient.ErrorResponse(err, errorRes) {
52 return fmt.Errorf("server error: %w", errorRes)
53 }
54
55 return fmt.Errorf("%s: %w", ErrSendFailed.Error(), err)
56 }
57
58 return nil
59 }
60
61 // Use direct HTTP client when custom headers are needed
62 body, err := s.sendRequestWithHeaders(client, url, request, headers)
63 if err != nil {
64 return err
65 }
66
67 err = json.Unmarshal(body, response)
68 if err != nil {
69 return fmt.Errorf("%s: %w", ErrParseResponse.Error(), err)
70 }
71
72 return nil
73 }
74
75 // extractErrorResponse attempts to extract a structured error from a failed request.
76 func (s *DefaultSender) extractErrorResponse(body []byte, errorRes *responseError) bool {
77 return json.Unmarshal(body, errorRes) == nil
78 }
79
80 // handleResponseError checks the response status and extracts error information if present.
81 func (s *DefaultSender) handleResponseError(res *http.Response, body []byte) error {
82 // Handle all HTTP error status codes (>= 400 covers both 4xx client errors and 5xx server errors)
83 if res.StatusCode >= http.StatusBadRequest {
84 errorRes := &responseError{}
85 if s.extractErrorResponse(body, errorRes) {
86 // Segment based on error category for more deterministic error handling
87 if res.StatusCode >= http.StatusInternalServerError {
88 // 5xx: Server-side errors (e.g., internal server error, bad gateway)
89 return fmt.Errorf("server error (%d): %w", res.StatusCode, errorRes)
90 }
91 // 4xx: Client-side errors (e.g., bad request, unauthorized, not found)
92 return fmt.Errorf("client error (%d): %w", res.StatusCode, errorRes)
93 }
94
95 // Fallback when no structured error response is available
96 if res.StatusCode >= http.StatusInternalServerError {
97 return fmt.Errorf("%w: %v", ErrUnexpectedStatus, res.Status)
98 }
99
100 return fmt.Errorf("%w: %v", ErrUnexpectedStatus, res.Status)
101 }
102
103 return nil
104 }
105
106 // sendRequestWithHeaders sends a request with custom headers using the underlying HTTP client.
107 // This method is used when per-request headers are needed, bypassing the jsonclient
108 // to avoid modifying shared header state.
109 // Parameters:
110 // - client: HTTP client to use
111 // - url: The complete API endpoint URL to send the request to
112 // - request: The JSON payload to send in the request body
113 // - headers: Custom headers to set on the request
114 //
115 // Returns: the response body as bytes if successful, or an error.
116 func (s *DefaultSender) sendRequestWithHeaders(
117 client *http.Client,
118 url string,
119 request *MessageRequest,
120 headers http.Header,
121 ) ([]byte, error) {
122 body, err := json.Marshal(request)
123 if err != nil {
124 return nil, fmt.Errorf("%s: %w", ErrMarshalRequest.Error(), err)
125 }
126
127 req, err := http.NewRequestWithContext(
128 context.Background(),
129 http.MethodPost,
130 url,
131 bytes.NewReader(body),
132 )
133 if err != nil {
134 return nil, fmt.Errorf("%s: %w", ErrCreateRequest.Error(), err)
135 }
136
137 s.setRequestHeaders(req, headers)
138
139 res, err := client.Do(req)
140 if err != nil {
141 return nil, fmt.Errorf("%s: %w", ErrSendRequest.Error(), err)
142 }
143
144 defer func() { _ = res.Body.Close() }()
145
146 body, err = io.ReadAll(res.Body)
147 if err != nil {
148 return nil, fmt.Errorf("%s: %w", ErrReadResponse.Error(), err)
149 }
150
151 if err := s.handleResponseError(res, body); err != nil {
152 return nil, err
153 }
154
155 return body, nil
156 }
157
158 // setRequestHeaders sets the Content-Type and custom headers on the HTTP request.
159 func (s *DefaultSender) setRequestHeaders(req *http.Request, headers http.Header) {
160 req.Header.Set("Content-Type", "application/json")
161
162 for key, values := range headers {
163 for _, value := range values {
164 req.Header.Add(key, value)
165 }
166 }
167 }