-
Notifications
You must be signed in to change notification settings - Fork 0
/
amoeba.go
111 lines (97 loc) · 2.23 KB
/
amoeba.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package amoeba
import (
"bytes"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
)
var (
PanicHandler func(interface{})
UpdateInterval int
)
const (
amoeba = "amoeba"
pathReq = "%s_req"
pathResp = "%s_resp"
)
func ReverseProxy(c *gin.Context) {
remote, err := url.Parse("http://127.0.0.1:8080")
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Director = func(req *http.Request) {
req.Header = c.Request.Header
req.Host = remote.Hostname()
req.URL.Scheme = remote.Scheme
req.URL.Host = remote.Host
req.URL.Path = c.Param("proxyPath")
req.RequestURI = req.URL.Path
}
proxy.Transport = &transport{http.DefaultTransport}
proxy.ServeHTTP(c.Writer, c.Request)
}
type transport struct {
http.RoundTripper
}
func (t *transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
pathKey := req.Header.Get(amoeba)
if len(pathKey) <= 0 {
return nil, errors.New("amoeba not set")
}
errReq := requestHandler(pathKey, req)
if errReq != nil {
// TODO ERROR
}
resp, err = t.RoundTripper.RoundTrip(req)
errResp := responseHandler(pathKey, resp)
if errResp != nil {
// TODO ERROR
}
return
}
func requestHandler(pathKey string, req *http.Request) error {
body := req.Body
if body == nil {
return nil
}
bodyByteArray, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
schema, ok := schemaMap[fmt.Sprintf(pathReq, pathKey)]
if !ok {
return errors.New("no request schema found")
}
result, err := Marshal(schema, string(bodyByteArray))
if err != nil {
// TODO ERROR
}
req.ContentLength = int64(len(result))
req.Body = ioutil.NopCloser(bytes.NewReader(result))
return nil
}
func responseHandler(pathKey string, resp *http.Response) error {
bRaw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
schema, ok := schemaMap[fmt.Sprintf(pathResp, pathKey)]
if !ok {
return errors.New("no response schema found")
}
bNew, err := Marshal(schema, string(bRaw))
if err != nil {
// TODO ERROR
}
body := ioutil.NopCloser(bytes.NewReader(bNew))
resp.Body = body
resp.ContentLength = int64(len(bRaw))
resp.Header.Set("Content-Length", strconv.Itoa(len(bNew)))
return nil
}