forked from goby-lang/goby
/
http_client.go
229 lines (181 loc) · 7.3 KB
/
http_client.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package vm
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/goby-lang/goby/vm/classes"
"github.com/goby-lang/goby/vm/errors"
)
// Instance methods --------------------------------------------------------
func builtinHTTPClientInstanceMethods() []*BuiltinMethodObject {
//TODO: cookie jar and mutable client
goClient := http.DefaultClient
return []*BuiltinMethodObject{
{
// Sends a GET request to the target and returns a `Net::HTTP::Response` object.
Name: "get",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgumentFormat, 1, len(args))
}
u, ok := args[0].(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, u.Class().Name)
}
resp, err := goClient.Get(u.value)
if err != nil {
return t.vm.initErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
gobyResp, err := responseGoToGoby(t, resp)
if err != nil {
return t.vm.initErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
}
},
}, {
// Sends a POST request to the target and returns a `Net::HTTP::Response` object.
Name: "post",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 3 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgumentFormat, 3, len(args))
}
u, ok := args[0].(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, u.Class().Name)
}
contentType, ok := args[1].(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, u.Class().Name)
}
body, ok := args[2].(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, u.Class().Name)
}
bodyR := strings.NewReader(body.value)
resp, err := goClient.Post(u.value, contentType.value, bodyR)
if err != nil {
return t.vm.initErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
gobyResp, err := responseGoToGoby(t, resp)
if err != nil {
return t.vm.initErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
}
},
}, {
// Sends a HEAD request to the target and returns a `Net::HTTP::Response` object.
Name: "head",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgumentFormat, 1, len(args))
}
u, ok := args[0].(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, u.Class().Name)
}
resp, err := goClient.Head(u.value)
if err != nil {
return t.vm.initErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
gobyResp, err := responseGoToGoby(t, resp)
if err != nil {
return t.vm.initErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
}
},
}, {
// Returns a blank `Net::HTTP::Request` object to be sent with the`exec` method
Name: "request",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
return httpRequestClass.initializeInstance()
}
},
}, {
// Sends a passed `Net::HTTP::Request` object and returns a `Net::HTTP::Response` object
Name: "exec",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgumentFormat, 1, len(args))
}
if args[0].Class().Name != httpRequestClass.Name {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, "HTTP Response", args[0].Class().Name)
}
goReq, err := requestGobyToGo(args[0])
if err != nil {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, err.Error())
}
goResp, err := goClient.Do(goReq)
if err != nil {
return t.vm.initErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
gobyResp, err := responseGoToGoby(t, goResp)
if err != nil {
return t.vm.initErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
}
},
},
}
}
// Internal functions ===================================================
// Functions for initialization -----------------------------------------
func initClientClass(vm *VM, hc *RClass) *RClass {
clientClass := vm.initializeClass("Client", false)
hc.setClassConstant(clientClass)
clientClass.setBuiltinMethods(builtinHTTPClientInstanceMethods(), false)
httpClientClass = clientClass
return clientClass
}
// Other helper functions -----------------------------------------------
func requestGobyToGo(gobyReq Object) (*http.Request, error) {
//:method, :protocol, :body, :content_length, :transfer_encoding, :host, :path, :url, :params
uObj, ok := gobyReq.instanceVariableGet("@url")
if !ok {
return nil, fmt.Errorf("could not get url")
}
u := uObj.(*StringObject).value
methodObj, ok := gobyReq.instanceVariableGet("@method")
if !ok {
return nil, fmt.Errorf("could not get method")
}
method := methodObj.(*StringObject).value
var body string
if !(method == "GET" || method == "HEAD") {
bodyObj, ok := gobyReq.instanceVariableGet("@body")
if !ok {
return nil, fmt.Errorf("could not get body")
}
body = bodyObj.(*StringObject).value
}
return http.NewRequest(method, u, strings.NewReader(body))
}
func responseGoToGoby(t *thread, goResp *http.Response) (Object, error) {
gobyResp := httpResponseClass.initializeInstance()
//attr_accessor :body, :status, :status_code, :protocol, :transfer_encoding, :http_version, :request_http_version, :request
//attr_reader :headers
body, err := ioutil.ReadAll(goResp.Body)
if err != nil {
return nil, err
}
gobyResp.instanceVariableSet("@body", t.vm.initStringObject(string(body)))
gobyResp.instanceVariableSet("@status_code", t.vm.initObjectFromGoType(goResp.StatusCode))
gobyResp.instanceVariableSet("@status", t.vm.initObjectFromGoType(goResp.Status))
gobyResp.instanceVariableSet("@protocol", t.vm.initObjectFromGoType(goResp.Proto))
gobyResp.instanceVariableSet("@transfer_encoding", t.vm.initObjectFromGoType(goResp.TransferEncoding))
underHeaders := map[string]Object{}
for k, v := range goResp.Header {
underHeaders[k] = t.vm.initObjectFromGoType(v)
}
gobyResp.instanceVariableSet("@headers", t.vm.initHashObject(underHeaders))
return gobyResp, nil
}