46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"io"
|
|
"log"
|
|
"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
|
|
}
|
|
|
|
// Fetch the image from the external URL
|
|
resp, err := http.Get(imageURL)
|
|
if err != nil {
|
|
log.Printf("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 {
|
|
log.Printf("Error writing image to response: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
}
|
|
}
|