-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy.go
57 lines (47 loc) · 1.09 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
package main
import (
"fmt"
"io"
"net/http"
"net/url"
)
type ContextCacheHeaderKey string
const (
ContextCacheIDKey ContextCacheHeaderKey = "id"
ContextCacheSkipKey ContextCacheHeaderKey = "skip"
)
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
type Proxy struct {
BackendAddr string
HTTPClient HTTPClient
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
u, err := url.Parse(p.BackendAddr)
if err != nil {
http.Error(w, fmt.Sprintf("invalid backend address: '%s'", p.BackendAddr), http.StatusInternalServerError)
return
}
u.Path = req.URL.Path
req.URL = u
// http: Request.RequestURI can't be set in client requests.
// http://golang.org/src/pkg/net/http/client.go
req.RequestURI = ""
resp, err := p.HTTPClient.Do(req)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
defer resp.Body.Close()
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}