2024-04-05 14:15:43 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-08-12 08:29:53 +02:00
|
|
|
"fmt"
|
2024-04-05 14:15:43 +02:00
|
|
|
"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
|
|
|
|
}
|
|
|
|
|
2024-08-12 08:29:53 +02:00
|
|
|
// 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
|
|
|
|
}
|
2024-04-05 14:15:43 +02:00
|
|
|
}
|
|
|
|
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 {
|
2024-08-11 21:45:52 +02:00
|
|
|
printWarn("Error writing image to response: %v", err)
|
2024-04-05 14:15:43 +02:00
|
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|