dumb/proxy.go

74 lines
1.4 KiB
Go
Raw Normal View History

2022-10-11 14:23:10 +01:00
package main
import (
"fmt"
"io"
"net/http"
2023-03-09 17:11:37 +01:00
"net/url"
"strings"
2022-10-11 14:23:10 +01:00
"github.com/gorilla/mux"
)
func isValidExt(ext string) bool {
valid := []string{"jpg", "jpeg", "png", "gif"}
for _, c := range valid {
if strings.ToLower(ext) == c {
return true
}
}
return false
}
2023-03-09 17:11:37 +01:00
func extractURL(image string) string {
u, err := url.Parse(image)
if err != nil {
return ""
}
return fmt.Sprintf("/images%s", u.Path)
}
2022-10-11 14:23:10 +01:00
func proxyHandler(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
f := v["filename"]
ext := v["ext"]
if !isValidExt(ext) {
w.WriteHeader(http.StatusBadRequest)
render("error", w, map[string]string{
"Status": "400",
"Error": "Something went wrong",
})
return
}
// first segment of URL resize the image to reduce bandwith usage.
url := fmt.Sprintf("https://t2.genius.com/unsafe/300x300/https://images.genius.com/%s.%s", f, ext)
2022-10-11 14:23:10 +01:00
res, err := sendRequest(url)
2022-10-11 14:23:10 +01:00
if err != nil {
logger.Errorln(err)
w.WriteHeader(http.StatusInternalServerError)
render("error", w, map[string]string{
"Status": "500",
"Error": "cannot reach genius servers",
})
2022-10-11 14:23:10 +01:00
return
}
if res.StatusCode != http.StatusOK {
w.WriteHeader(http.StatusInternalServerError)
render("error", w, map[string]string{
"Status": "500",
"Error": "something went wrong",
})
2022-10-11 14:23:10 +01:00
return
}
w.Header().Add("Content-type", fmt.Sprintf("image/%s", ext))
2022-10-11 14:23:10 +01:00
io.Copy(w, res.Body)
}