forked from goby-lang/goby
/
http.go
215 lines (168 loc) · 6.88 KB
/
http.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
package vm
import (
"io/ioutil"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"github.com/goby-lang/goby/vm/errors"
)
var (
httpRequestClass *RClass
httpResponseClass *RClass
httpClientClass *RClass
)
// Class methods --------------------------------------------------------
func builtinHTTPClassMethods() []*BuiltinMethodObject {
return []*BuiltinMethodObject{
{
// Sends a GET request to the target and returns the HTTP response as a string. Will error on non-200 responses, for more control over http requests look at the `start` method.
Name: "get",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
arg0, ok := args[0].(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect argument 0 to be string, got: %s", args[0].Class().Name)
}
uri, err := url.Parse(arg0.value)
if len(args) > 1 {
var arr []string
for i, v := range args[1:] {
argn, ok := v.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Splat arguments must be a string, got: %s for argument %d", v.Class().Name, i)
}
arr = append(arr, argn.value)
}
uri.Path = path.Join(arr...)
}
resp, err := http.Get(uri.String())
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
if resp.StatusCode != http.StatusOK {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Non-200 response, %s (%d)", resp.Status, resp.StatusCode)
}
content, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, err.Error())
}
return t.vm.InitStringObject(string(content))
},
}, {
// Sends a POST request to the target with type header and body. Returns the HTTP response as a string. Will error on non-200 responses, for more control over http requests look at the `start` method.
Name: "post",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 3 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgumentFormat, 3, len(args))
}
arg0, ok := args[0].(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect argument 0 to be string, got: %s", args[0].Class().Name)
}
host := arg0.value
arg1, ok := args[1].(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect argument 1 to be string, got: %s", args[0].Class().Name)
}
contentType := arg1.value
arg2, ok := args[2].(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect argument 2 to be string, got: %s", args[0].Class().Name)
}
body := arg2.value
resp, err := http.Post(host, contentType, strings.NewReader(body))
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
if resp.StatusCode != http.StatusOK {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Non-200 response, %s (%d)", resp.Status, resp.StatusCode)
}
content, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, err.Error())
}
return t.vm.InitStringObject(string(content))
},
}, {
// Sends a HEAD request to the target with type header and body. Returns the HTTP headers as a map[string]string. Will error on non-200 responses, for more control over http requests look at the `start` method.
Name: "head",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
arg0, ok := args[0].(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect argument 0 to be string, got: %s", args[0].Class().Name)
}
uri, err := url.Parse(arg0.value)
if len(args) > 1 {
var arr []string
for i, v := range args[1:] {
argn, ok := v.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Splat arguments must be a string, got: %s for argument %d", v.Class().Name, i)
}
arr = append(arr, argn.value)
}
uri.Path = path.Join(arr...)
}
resp, err := http.Head(uri.String())
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
if resp.StatusCode != http.StatusOK {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Non-200 response, %s (%d)", resp.Status, resp.StatusCode)
}
ret := t.vm.InitHashObject(map[string]Object{})
for k, v := range resp.Header {
ret.Pairs[k] = t.vm.InitStringObject(strings.Join(v, " "))
}
return ret
},
}, {
// Starts an HTTP client. This method requires a block which takes a Net::HTTP::Client object. The return value of this method is the last evaluated value of the provided block.
Name: "start",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 arguments. got=%v", strconv.Itoa(len(args)))
}
gobyClient := httpClientClass.initializeInstance()
result := t.builtinMethodYield(blockFrame, gobyClient)
if err, ok := result.Target.(*Error); ok {
return err //an Error object
}
return result.Target
},
},
}
}
// Internal functions ===================================================
// Functions for initialization -----------------------------------------
func initHTTPClass(vm *VM) {
net := vm.loadConstant("Net", true)
http := vm.initializeClass("HTTP")
http.setBuiltinMethods(builtinHTTPClassMethods(), true)
initRequestClass(vm, http)
initResponseClass(vm, http)
initClientClass(vm, http)
net.setClassConstant(http)
// Use Goby code to extend request and response classes.
vm.mainThread.execGobyLib("net/http/response.gb")
vm.mainThread.execGobyLib("net/http/request.gb")
}
func initRequestClass(vm *VM, hc *RClass) *RClass {
requestClass := vm.initializeClass("Request")
hc.setClassConstant(requestClass)
builtinHTTPRequestInstanceMethods := []*BuiltinMethodObject{}
requestClass.setBuiltinMethods(builtinHTTPRequestInstanceMethods, false)
httpRequestClass = requestClass
return requestClass
}
func initResponseClass(vm *VM, hc *RClass) *RClass {
responseClass := vm.initializeClass("Response")
hc.setClassConstant(responseClass)
builtinHTTPResponseInstanceMethods := []*BuiltinMethodObject{}
responseClass.setBuiltinMethods(builtinHTTPResponseInstanceMethods, false)
httpResponseClass = responseClass
return responseClass
}