2024-04-05 14:15:43 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2024-10-19 14:02:27 +02:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2024-04-05 14:15:43 +02:00
|
|
|
)
|
|
|
|
|
2024-11-19 10:36:33 +01:00
|
|
|
func serveImageProxy(w http.ResponseWriter, imageURL string) {
|
2024-09-12 22:11:39 +02:00
|
|
|
// Fetch the image from the external URL
|
|
|
|
resp, err := http.Get(imageURL)
|
|
|
|
if err != nil {
|
|
|
|
printWarn("Error fetching image: %v", err)
|
2024-11-19 10:36:33 +01:00
|
|
|
serveMissingImage(w, nil)
|
2024-09-12 22:11:39 +02:00
|
|
|
return
|
2024-04-05 14:15:43 +02:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
// Check if the request was successful
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
2024-11-19 10:36:33 +01:00
|
|
|
serveMissingImage(w, nil)
|
2024-04-05 14:15:43 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the Content-Type header to the type of the fetched image
|
|
|
|
contentType := resp.Header.Get("Content-Type")
|
2024-10-19 14:02:27 +02:00
|
|
|
if contentType != "" && strings.HasPrefix(contentType, "image/") {
|
2024-04-05 14:15:43 +02:00
|
|
|
w.Header().Set("Content-Type", contentType)
|
|
|
|
} else {
|
2024-11-19 10:36:33 +01:00
|
|
|
serveMissingImage(w, nil)
|
2024-10-19 14:02:27 +02:00
|
|
|
return
|
2024-04-05 14:15:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write the image content to the response
|
|
|
|
if _, err := io.Copy(w, resp.Body); err != nil {
|
2024-08-11 21:45:52 +02:00
|
|
|
printWarn("Error writing image to response: %v", err)
|
2024-10-19 14:02:27 +02:00
|
|
|
// Serve missing.svg
|
|
|
|
// Note: At this point, headers are already sent, so serving missing.svg won't work.
|
|
|
|
// It's better to just log the error here.
|
2024-04-05 14:15:43 +02:00
|
|
|
}
|
|
|
|
}
|
2024-10-19 14:02:27 +02:00
|
|
|
|
|
|
|
// Serve missing.svg
|
|
|
|
func serveMissingImage(w http.ResponseWriter, r *http.Request) {
|
|
|
|
missingImagePath := filepath.Join("static", "images", "missing.svg")
|
|
|
|
w.Header().Set("Content-Type", "image/svg+xml")
|
|
|
|
w.Header().Set("Cache-Control", "no-store, must-revalidate")
|
|
|
|
w.Header().Set("Pragma", "no-cache")
|
|
|
|
w.Header().Set("Expires", "0")
|
|
|
|
http.ServeFile(w, r, missingImagePath)
|
|
|
|
}
|