forked from openatx/wdaproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrevproxy.go
More file actions
60 lines (54 loc) · 1.39 KB
/
revproxy.go
File metadata and controls
60 lines (54 loc) · 1.39 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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
// "fmt"
)
type transport struct {
http.RoundTripper
}
func (t *transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
// rewrite url
if strings.HasPrefix(req.RequestURI, "/origin/") {
req.URL.Path = req.RequestURI[len("/origin"):]
return t.RoundTripper.RoundTrip(req)
}
// request
resp, err = t.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
// rewrite body
if req.RequestURI == "/status" {
jsonResp := &statusResp{}
err = json.NewDecoder(resp.Body).Decode(jsonResp)
if err != nil {
return nil, err
}
resp.Body.Close()
jsonResp.Value["device"] = map[string]interface{}{
"udid": udid,
"name": udidNames[udid],
}
data, _ := json.Marshal(jsonResp)
// update body and fix length
resp.Body = ioutil.NopCloser(bytes.NewReader(data))
resp.ContentLength = int64(len(data))
resp.Header.Set("Content-Length", strconv.Itoa(len(data)))
return resp, nil
}
return resp, nil
}
func NewReverseProxyHandlerFunc(targetURL *url.URL) http.HandlerFunc {
httpProxy := httputil.NewSingleHostReverseProxy(targetURL)
httpProxy.Transport = &transport{http.DefaultTransport}
return func(rw http.ResponseWriter, r *http.Request) {
httpProxy.ServeHTTP(rw, r)
}
}