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