-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
http_proxy_js_response.go
133 lines (113 loc) · 2.47 KB
/
http_proxy_js_response.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package modules
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/elazarl/goproxy"
)
type JSResponse struct {
Status int
ContentType string
Headers []JSHeader
Body string
refHash string
resp *http.Response
bodyRead bool
}
func NewJSResponse(res *http.Response) *JSResponse {
cType := ""
headers := make([]JSHeader, 0)
code := 200
if res != nil {
code = res.StatusCode
for name, values := range res.Header {
for _, value := range values {
headers = append(headers, JSHeader{name, value})
if name == "Content-Type" {
cType = value
}
}
}
}
resp := &JSResponse{
Status: code,
ContentType: cType,
Headers: headers,
resp: res,
bodyRead: false,
}
resp.UpdateHash()
return resp
}
func (j *JSResponse) NewHash() string {
hash := fmt.Sprintf("%d.%s", j.Status, j.ContentType)
for _, h := range j.Headers {
hash += fmt.Sprintf(".%s-%s", h.Name, h.Value)
}
return hash
}
func (j *JSResponse) UpdateHash() {
j.refHash = j.NewHash()
}
func (j *JSResponse) WasModified() bool {
// body was read
if j.bodyRead == true {
return true
}
// check if any of the fields has been changed
newHash := j.NewHash()
if newHash != j.refHash {
return true
}
return false
}
func (j *JSResponse) GetHeader(name, deflt string) string {
name = strings.ToLower(name)
for _, h := range j.Headers {
if name == strings.ToLower(h.Name) {
return h.Value
}
}
return deflt
}
func (j *JSResponse) SetHeader(name, value string) {
name = strings.ToLower(name)
for i, h := range j.Headers {
if name == strings.ToLower(h.Name) {
j.Headers[i].Value = value
return
}
}
j.Headers = append(j.Headers, JSHeader{name, value})
}
func (j *JSResponse) RemoveHeader(name string) {
name = strings.ToLower(name)
for i, h := range j.Headers {
if name == strings.ToLower(h.Name) {
j.Headers = append(j.Headers[:i], j.Headers[i+1:]...)
}
}
}
func (j *JSResponse) ToResponse(req *http.Request) (resp *http.Response) {
resp = goproxy.NewResponse(req, j.ContentType, j.Status, j.Body)
if len(j.Headers) > 0 {
for _, h := range j.Headers {
resp.Header.Add(h.Name, h.Value)
}
}
return
}
func (j *JSResponse) ReadBody() string {
defer j.resp.Body.Close()
raw, err := ioutil.ReadAll(j.resp.Body)
if err != nil {
return ""
}
j.Body = string(raw)
j.bodyRead = true
// reset the response body to the original unread state
j.resp.Body = ioutil.NopCloser(bytes.NewBuffer(raw))
return j.Body
}