(option FileHandlerOption)
| 331 | } |
| 332 | |
| 333 | func determineMimeType(option FileHandlerOption) (string, []byte) { |
| 334 | // If MimeType is set, use it directly |
| 335 | if option.MimeType != "" { |
| 336 | return option.MimeType, nil |
| 337 | } |
| 338 | |
| 339 | // Detect from Data if available, no need to buffer |
| 340 | if option.Data != nil { |
| 341 | return http.DetectContentType(option.Data), nil |
| 342 | } |
| 343 | |
| 344 | // Detect from FilePath, no buffering necessary |
| 345 | if option.FilePath != "" { |
| 346 | filePath := wavebase.ExpandHomeDirSafe(option.FilePath) |
| 347 | file, err := os.Open(filePath) |
| 348 | if err != nil { |
| 349 | return "application/octet-stream", nil // Fallback on error |
| 350 | } |
| 351 | defer file.Close() |
| 352 | |
| 353 | // Read first 512 bytes for MIME detection |
| 354 | buf := make([]byte, 512) |
| 355 | _, err = file.Read(buf) |
| 356 | if err != nil && err != io.EOF { |
| 357 | return "application/octet-stream", nil |
| 358 | } |
| 359 | return http.DetectContentType(buf), nil |
| 360 | } |
| 361 | |
| 362 | // Buffer for File (fs.File), since it lacks Seek |
| 363 | if option.File != nil { |
| 364 | buf := make([]byte, 512) |
| 365 | n, err := option.File.Read(buf) |
| 366 | if err != nil && err != io.EOF { |
| 367 | return "application/octet-stream", nil |
| 368 | } |
| 369 | return http.DetectContentType(buf[:n]), buf[:n] |
| 370 | } |
| 371 | |
| 372 | // Buffer for Reader (io.Reader), same as File |
| 373 | if option.Reader != nil { |
| 374 | buf := make([]byte, 512) |
| 375 | n, err := option.Reader.Read(buf) |
| 376 | if err != nil && err != io.EOF { |
| 377 | return "application/octet-stream", nil |
| 378 | } |
| 379 | return http.DetectContentType(buf[:n]), buf[:n] |
| 380 | } |
| 381 | |
| 382 | // Default MIME type if none specified |
| 383 | return "application/octet-stream", nil |
| 384 | } |
| 385 | |
| 386 | // ServeFileOption handles serving content based on the provided FileHandlerOption |
| 387 | func ServeFileOption(w http.ResponseWriter, r *http.Request, option FileHandlerOption) error { |
no test coverage detected