This repository has been archived by the owner on May 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
request_forwarder.go
80 lines (62 loc) · 1.8 KB
/
request_forwarder.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
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
// Request is the http request that will be forwarded to the downstream service.
type Request struct {
LocalstackHost string
*http.Request
http.ResponseWriter
Done chan bool // channel to notify when the request has finsihed.
}
func forward(req *Request, backend Backend) {
reqURL, _ := url.Parse(req.Request.URL.String())
reqURL.Scheme = "http"
if req.LocalstackHost != "" {
backend.Host = req.LocalstackHost
}
reqURL.Host = backend.String()
reqBody, _ := ioutil.ReadAll(req.Request.Body)
newRequest, newReqErr := http.NewRequest(req.Request.Method,
reqURL.String(), bytes.NewBuffer(reqBody))
if newReqErr != nil {
log.Printf("[WARNING]: Failed forwarding the request to %s: %v",
backend.String(), newReqErr)
req.ResponseWriter.WriteHeader(http.StatusUnprocessableEntity)
req.ResponseWriter.Write([]byte(newReqErr.Error()))
req.Done <- true
return
}
copyRequestHeaders(req.Request, newRequest)
log.Printf("[INFO]: Request at [%s]{} is forwarded to [%s]",
req.Request.URL.String(),
newRequest.Host)
client := http.Client{}
res, reqErr := client.Do(newRequest)
if reqErr != nil {
req.ResponseWriter.WriteHeader(http.StatusBadGateway)
req.ResponseWriter.Write([]byte(reqErr.Error()))
req.Done <- true
return
}
copyResponseHeaders(res, req)
req.ResponseWriter.WriteHeader(res.StatusCode)
io.Copy(req.ResponseWriter, res.Body)
req.Done <- true
}
func copyRequestHeaders(originalRequest, newRequest *http.Request) {
for k, v := range originalRequest.Header {
newRequest.Header.Add(k, strings.Join(v, " "))
}
}
func copyResponseHeaders(newResponse *http.Response, req *Request) {
for k, v := range newResponse.Header {
req.ResponseWriter.Header().Add(k, strings.Join(v, " "))
}
}