-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.go
More file actions
76 lines (66 loc) · 1.77 KB
/
proxy.go
File metadata and controls
76 lines (66 loc) · 1.77 KB
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
package proxy
import (
"context"
"io"
"net/http"
"net/url"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
// ProxyHandler
// This function returns a http handler func that can be used in almost all of the we frameworks
func ProxyHandler(ctx context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
val := ctx.Value("url")
v, ok := val.(*url.URL)
if !ok {
return
}
// Get the params with gorilla mux
// Because the http handlers are managed in the gorilla/mux router
r := mux.Vars(req)
// Reading required value of the map
path := r["rest"]
// Constructing a new url according to
// the incoming request and the target url
req.URL = &url.URL{
Scheme: v.Scheme,
Host: v.Host,
Path: "/" + path,
RawPath: v.RawPath,
RawQuery: v.RawQuery,
Fragment: v.Fragment,
RawFragment: v.RawFragment,
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Copy the incoming headers to the outgoing headers
copyHeader(w.Header(), resp.Header)
// Set http status code
w.WriteHeader(resp.StatusCode)
// copy the incoming response body to the outgoing response writer
_, _ = io.Copy(w, resp.Body)
// Logging the progress
defer func() {
logrus.StandardLogger().
WithField("request_body", req.Body).
WithField("request_url", req.URL.String()).
WithField("request_headers", req.Header).
WithField("method", req.Method).
WithField("response", resp.Body).
Infoln()
_ = resp.Body.Close()
}()
}
}
// Copy header of src into the destination
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}