Search/imageproxy.go
2024-08-12 08:29:53 +02:00

54 lines
1.6 KiB
Go

package main
import (
"fmt"
"io"
"net/http"
)
func handleImageProxy(w http.ResponseWriter, r *http.Request) {
// Get the URL of the image from the query string
imageURL := r.URL.Query().Get("url")
if imageURL == "" {
http.Error(w, "URL parameter is required", http.StatusBadRequest)
return
}
// Try to fetch the image from Bing first
bingURL := fmt.Sprintf("https://tse.mm.bing.net/th?q=%s", imageURL)
resp, err := http.Get(bingURL)
if err != nil || resp.StatusCode != http.StatusOK {
// If fetching from Bing fails, attempt to fetch from the original image URL
printWarn("Error fetching image from Bing, trying original URL.")
// Attempt to fetch the image directly
resp, err = http.Get(imageURL)
if err != nil {
printWarn("Error fetching image: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
defer resp.Body.Close()
// Check if the request was successful
if resp.StatusCode != http.StatusOK {
http.Error(w, "Failed to fetch image", http.StatusBadGateway)
return
}
// Set the Content-Type header to the type of the fetched image
contentType := resp.Header.Get("Content-Type")
if contentType != "" {
w.Header().Set("Content-Type", contentType)
} else {
// Default to octet-stream if Content-Type is not available
w.Header().Set("Content-Type", "application/octet-stream")
}
// Write the image content to the response
if _, err := io.Copy(w, resp.Body); err != nil {
printWarn("Error writing image to response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}