-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathrequest.go
104 lines (79 loc) · 1.85 KB
/
request.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
package main
import(
"net/http"
"sync"
"encoding/json"
"strings"
"io"
"io/ioutil"
)
type Request struct {
Header http.Header `json:"headers"`
ContentLength int64 `json:"content_length"`
Body string `json:"body"`
Method string `json:"method"`
Path string `json:"path"`
Query string `json:"query"`
}
type RequestDatabase struct {
*sync.RWMutex
requests []*Request
maxRequests int
Count int
}
func MakeRequest(req *http.Request) *Request {
r := new(Request)
r.Header = make(http.Header)
for k, v := range req.Header {
r.Header[k] = v
}
r.ContentLength = req.ContentLength
r.Method = req.Method
r.Path = req.URL.Path
r.Query = req.URL.RawQuery
body, _ := ioutil.ReadAll(req.Body)
r.Body = string(body)
return r
}
func (r *Request) ToJson() ([]byte, error) {
return json.Marshal(r)
}
func (r *Request) Forward(client *http.Client, url string) {
body := strings.NewReader(r.Body)
req, _ := http.NewRequest(r.Method, url, body)
for header, vals := range r.Header {
for _, val := range vals {
req.Header.Add(header, val)
}
}
resp, _ := client.Do(req)
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
/////////////////////////////
// Request Database
/////////////////////////////
func (d *RequestDatabase) Insert(req *http.Request) *Request {
d.Lock()
r := MakeRequest(req)
d.requests = append([]*Request{r}, d.requests...)
if len(d.requests) >= d.maxRequests {
d.requests = d.requests[0:d.maxRequests]
}
d.Count += 1
d.Unlock()
return r
}
func (d *RequestDatabase) Clear() {
d.Lock()
d.requests = make([]*Request, 0, d.maxRequests)
d.Count = 0
d.Unlock();
}
func (d *RequestDatabase) ToJson() ([]byte, error) {
return json.Marshal(d.requests)
}
func MakeRequestDatabase(capacity int) *RequestDatabase {
db := &RequestDatabase{new(sync.RWMutex), make([]*Request, 0, capacity), capacity, 0}
return db
}