forked from rramiachraf/dumb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
73 lines (60 loc) · 1.38 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
"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
}
func extractURL(image string) string {
u, err := url.Parse(image)
if err != nil {
return ""
}
return fmt.Sprintf("/images%s", u.Path)
}
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)
res, err := sendRequest(url)
if err != nil {
logger.Errorln(err)
w.WriteHeader(http.StatusInternalServerError)
render("error", w, map[string]string{
"Status": "500",
"Error": "cannot reach genius servers",
})
return
}
if res.StatusCode != http.StatusOK {
w.WriteHeader(http.StatusInternalServerError)
render("error", w, map[string]string{
"Status": "500",
"Error": "something went wrong",
})
return
}
w.Header().Add("Content-type", fmt.Sprintf("image/%s", ext))
io.Copy(w, res.Body)
}