-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.go
183 lines (159 loc) · 4.33 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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package nethttp
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"go.starlark.net/starlark"
)
func fnHttpRequest(t *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
request, err := newRequestFromStarlarkArgs("GET", args, kwargs)
if err != nil {
return nil, err
}
return NewHttpRequest(request)
}
func NewHttpRequest(request *http.Request) (*HttpRequest, error) {
attrs, err := GetHttpRequestAttrs(request)
if err != nil {
return nil, err
}
return &HttpRequest{
request: request,
attrs: *attrs,
}, nil
}
type HttpRequest struct {
request *http.Request
attrs starlark.StringDict
}
var _ starlark.HasAttrs = (*HttpRequest)(nil)
func (r *HttpRequest) String() string {
return fmt.Sprintf("Request(%s)", r.attrs.String())
}
func (r *HttpRequest) Type() string { return "module" }
func (r *HttpRequest) Freeze() { r.attrs.Freeze() }
func (r *HttpRequest) Truth() starlark.Bool { return starlark.True }
func (r *HttpRequest) Hash() (uint32, error) {
return 0, fmt.Errorf("unhashable type: %s", r.Type())
}
func (r *HttpRequest) Attr(name string) (starlark.Value, error) {
if val, ok := r.attrs[name]; ok {
return val, nil
}
return nil, nil
}
func (r *HttpRequest) AttrNames() []string {
var names []string
for name := range r.attrs {
names = append(names, name)
}
sort.Strings(names)
return names
}
func GetHttpRequestAttrs(request *http.Request) (*starlark.StringDict, error) {
bytes, err := ioutil.ReadAll(request.Body)
if err != nil {
return nil, err
}
return &starlark.StringDict{
"method": starlark.String(request.Method),
"url": starlark.String(request.URL.String()),
"host": starlark.String(request.Host),
"body": starlark.String(string(bytes)),
"content_length": starlark.MakeInt(int(request.ContentLength)),
"headers": getDictFromHeaders(request.Header),
}, nil
}
func newRequestFromStarlarkArgs(method string, args starlark.Tuple, kwargs []starlark.Tuple) (*http.Request, error) {
request := &http.Request{
Method: method,
}
var rawurl, body string
headers := &starlark.Dict{}
if err := starlark.UnpackArgs("http.Request", args, kwargs,
"url", &rawurl,
"method?", &request.Method,
"host?", &request.Host,
"body?", &body,
"headers?", &headers,
); err != nil {
return nil, err
}
parsedURL, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
header, err := getHeadersFromDict(headers)
if err != nil {
return nil, err
}
request.URL = parsedURL
request.Body = ioutil.NopCloser(strings.NewReader(body))
request.ContentLength = int64(len(body))
request.Header = header
return request, nil
}
func getHeadersFromDict(dict *starlark.Dict) (http.Header, error) {
headers := http.Header(make(map[string][]string))
for _, item := range dict.Items() {
k, ok := item[0].(*starlark.String)
if !ok {
return nil, fmt.Errorf("Expected string key type for: %+v", item)
}
key := k.GoString()
switch t := item[1].(type) {
case starlark.String:
headers[key] = append(headers[key], t.GoString())
case *starlark.List:
headers[key] = getStringSliceFromStarlarkList(t)
}
v, ok := item[1].(starlark.String)
if !ok {
return nil, fmt.Errorf("Expected string value type for: %+v", item)
}
value := v.GoString()
headers[key] = append(headers[key], value)
}
return headers, nil
}
func getStringSliceFromStarlarkList(list *starlark.List) []string {
size := list.Len()
slice := make([]string, size)
for i := 0; i < size; i++ {
value := list.Index(i)
var str string
switch t := value.(type) {
case starlark.String:
str = t.GoString()
default:
str = t.String()
}
slice[i] = str
}
return slice
}
func getDictFromHeaders(headers http.Header) *starlark.Dict {
dict := &starlark.Dict{}
for key, values := range headers {
dict.SetKey(starlark.String(key), getSkylarkList(values))
}
return dict
}
func getSkylarkList(values []string) *starlark.List {
list := &starlark.List{}
for _, v := range values {
list.Append(starlark.String(v))
}
return list
}
// AsHttpRequest attempts a type assertion and returns the typed request or False
// if the type assertion failed.
func AsHttpRequest(value starlark.Value) (*HttpRequest, bool) {
if req, ok := value.(*HttpRequest); ok {
return req, true
}
return nil, false
}