Search/imageproxy.go

53 lines
1.4 KiB
Go
Raw Normal View History

2024-04-05 14:15:43 +02:00
package main
import (
"io"
"net/http"
"path/filepath"
"strings"
2024-04-05 14:15:43 +02: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)
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 {
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")
if contentType != "" && strings.HasPrefix(contentType, "image/") {
2024-04-05 14:15:43 +02:00
w.Header().Set("Content-Type", contentType)
} else {
serveMissingImage(w, nil)
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 {
printWarn("Error writing image to response: %v", err)
// 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
}
}
// 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)
}