-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_http.go
87 lines (74 loc) · 2.14 KB
/
handle_http.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import(
"fmt"
"io"
"io/ioutil"
"net/http"
s "strings"
)
func min(left int, right int) int {
if left < right {
return left
} else {
return right
}
}
// Handle HTTP GET method
// Pass response from origin
// dbJob will be set if there is a file to be saved to cache
func HandleHttp(dbJob **DbJob, responseW http.ResponseWriter, request *http.Request, l Logger) {
url := request.URL.String()
const dispWrap = 120
l.Log("G", url[:min(dispWrap, len(url))])
if isPicture(url) {
l.Log("")
pic := DbGet(url)
if pic == nil {
if CacheOnly {
http.Error(responseW, "", http.StatusNotFound)
return
}
//Else - continue handling the request
} else {
l.Log("GC")
// Its not clear from the ResponseWriter source comments whether this
// can be omitted
responseW.Header().Add("Content-Lentgth", fmt.Sprintf("%s", len(*pic)))
_, err := responseW.Write(*pic) // will write headers as well
if err != nil {
l.Log("GCX")
}
return
}
}
origResponse, err := http.DefaultTransport.RoundTrip(request)
if err != nil {
http.Error(responseW, "Bad Gateway", http.StatusBadGateway)
l.Log("GXS", err.Error())
return
}
defer origResponse.Body.Close()
copyHeader(responseW.Header(), origResponse.Header)
responseW.WriteHeader(origResponse.StatusCode)
respBodyT := io.TeeReader(origResponse.Body, responseW)
l.Log("G", "responding")
byPic, err := ioutil.ReadAll(respBodyT)
if err != nil {
l.Log("GXR", err.Error())
return
}
if isPicture(url) {
l.Log("GCS", "saving", url)
*dbJob = &DbJob{url, &byPic}
}
}
// Header is map[string][] string
func copyHeader(dest, source http.Header) {
for name, values := range source {
dest.Set(name, values[0])
//fmt.Println(name, values)
}
}
func isPicture(url string) bool {
return s.HasSuffix(url, ".jpg") || s.HasSuffix(url, ".png")
}