-
Notifications
You must be signed in to change notification settings - Fork 72
/
proxy_handler.go
43 lines (38 loc) · 946 Bytes
/
proxy_handler.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
package handlers
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
type ProxyHandler struct {
Stats *Stats
}
func (h *ProxyHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
destination := strings.TrimPrefix(req.URL.Path, "/proxy/")
destination = "http://" + destination
client := &http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
},
}
before := time.Now()
getResp, err := client.Get(destination)
if err != nil {
fmt.Fprintf(os.Stderr, "request failed: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(fmt.Sprintf("request failed: %s", err)))
return
}
defer getResp.Body.Close()
h.Stats.Add(time.Since(before).Seconds())
readBytes, err := ioutil.ReadAll(getResp.Body)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(fmt.Sprintf("read body failed: %s", err)))
return
}
resp.Write(readBytes)
}