(ctx context.Context, c cache.Cache, attachmentURL string)
| 182 | } |
| 183 | |
| 184 | func validateAttachmentURL(ctx context.Context, c cache.Cache, attachmentURL string) error { |
| 185 | cacheKey := "mms-url-validation:" + attachmentURL |
| 186 | |
| 187 | if cachedVal, err := c.Get(ctx, cacheKey); err == nil { |
| 188 | if cachedVal == "valid" { |
| 189 | return nil |
| 190 | } |
| 191 | return fmt.Errorf(cachedVal) |
| 192 | } |
| 193 | |
| 194 | client := &http.Client{ |
| 195 | Timeout: 5 * time.Second, |
| 196 | } |
| 197 | |
| 198 | req, err := http.NewRequest(http.MethodHead, attachmentURL, nil) |
| 199 | if err != nil { |
| 200 | errMsg := fmt.Sprintf("invalid url format") |
| 201 | saveToCache(ctx, c, cacheKey, errMsg) |
| 202 | return fmt.Errorf(errMsg) |
| 203 | } |
| 204 | |
| 205 | resp, err := client.Do(req) |
| 206 | if err != nil { |
| 207 | errMsg := fmt.Sprintf("could not reach the url") |
| 208 | saveToCache(ctx, c, cacheKey, errMsg) |
| 209 | return fmt.Errorf(errMsg) |
| 210 | } |
| 211 | defer resp.Body.Close() |
| 212 | |
| 213 | if resp.StatusCode < 200 || resp.StatusCode >= 400 { |
| 214 | errMsg := fmt.Sprintf("url returned an error status code: %d", resp.StatusCode) |
| 215 | saveToCache(ctx, c, cacheKey, errMsg) |
| 216 | return fmt.Errorf(errMsg) |
| 217 | } |
| 218 | |
| 219 | const maxSizeBytes = 1.5 * 1024 * 1024 |
| 220 | |
| 221 | if resp.ContentLength > int64(maxSizeBytes) { |
| 222 | errMsg := fmt.Sprintf("file size (%.2f MB) exceeds the 1.5 MB carrier limit", float64(resp.ContentLength)/(1024*1024)) |
| 223 | saveToCache(ctx, c, cacheKey, errMsg) |
| 224 | return fmt.Errorf(errMsg) |
| 225 | } |
| 226 | |
| 227 | saveToCache(ctx, c, cacheKey, "valid") |
| 228 | return nil |
| 229 | } |
| 230 | |
| 231 | func saveToCache(ctx context.Context, c cache.Cache, key string, value string) { |
| 232 | _ = c.Set(ctx, key, value, 15*time.Minute) |
nothing calls this directly
no test coverage detected