-
Notifications
You must be signed in to change notification settings - Fork 71
/
proxy_handler.go
49 lines (43 loc) · 1.02 KB
/
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
44
45
46
47
48
49
package handlers
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"time"
)
type ProxyHandler struct {
Stats *Stats
}
var httpClient = &http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
Dial: (&net.Dialer{
Timeout: 4 * time.Second,
KeepAlive: 0,
}).Dial,
},
}
func (h *ProxyHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
destination := strings.TrimPrefix(req.URL.Path, "/proxy/")
destination = "http://" + destination
before := time.Now()
getResp, err := httpClient.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)
}