-
Notifications
You must be signed in to change notification settings - Fork 171
/
simple_server.go
252 lines (198 loc) · 6.12 KB
/
simple_server.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package vm
import (
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"unicode"
"fmt"
"strconv"
"github.com/fatih/structs"
"github.com/goby-lang/goby/vm/classes"
"github.com/gorilla/mux"
)
type request struct {
Method string
Body string
URL string
Path string
Host string
Protocol string
Headers map[string][]string
ContentLength int64
TransferEncoding []string
}
type response struct {
status int
body string
contentType string
}
// Instance methods -----------------------------------------------------
func builtinSimpleServerInstanceMethods() []*BuiltinMethodObject {
router := mux.NewRouter()
return []*BuiltinMethodObject{
{
Name: "mount",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
path := args[0].(*StringObject).value
method := args[1].(*StringObject).value
router.HandleFunc(path, newHandler(t, blockFrame)).Methods(method)
return receiver
},
},
{
Name: "static",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
prefix := args[0].(*StringObject).value
fileName := args[1].(*StringObject).value
router.PathPrefix(prefix).Handler(http.StripPrefix(prefix, http.FileServer(http.Dir(fileName))))
return receiver
},
},
{
Name: "start",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
var port string
var serveStatic bool
server := receiver.(*RObject)
portVar, ok := server.InstanceVariableGet("@port")
if !ok {
port = "8080"
} else {
switch p := portVar.(type) {
case *StringObject:
port = p.value
case *IntegerObject:
port = strconv.Itoa(p.value)
default:
fmt.Printf("Unexpected type %s for port setting\n", portVar.Class().Name)
}
}
log.Println("SimpleServer start listening on port: " + port)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
log.Println("SimpleServer gracefully stopped")
os.Exit(0)
}
}()
fileRoot, serveStatic := server.InstanceVariables.get("@file_root")
router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s %d\n", r.Method, r.URL.Path, r.Proto, 404)
})
if serveStatic && fileRoot.Class() != t.vm.objectClass.getClassConstant(classes.NullClass) {
fr := fileRoot.(*StringObject).value
currentDir, _ := os.Getwd()
fp := filepath.Join(currentDir, fr)
fs := http.FileServer(http.Dir(fp))
http.Handle("/", fs)
} else {
http.Handle("/", router)
}
err := http.ListenAndServe(":"+port, nil)
if err != http.ErrServerClosed { // HL
log.Fatalf("listen: %s\n", err)
}
return receiver
},
},
}
}
// Internal functions ===================================================
// Functions for initialization -----------------------------------------
func initSimpleServerClass(vm *VM) {
initHTTPClass(vm)
net := vm.loadConstant("Net", true)
simpleServer := vm.initializeClass("SimpleServer")
simpleServer.setBuiltinMethods(builtinSimpleServerInstanceMethods(), false)
net.setClassConstant(simpleServer)
vm.mainThread.execGobyLib("net/simple_server.gb")
}
// Other helper functions -----------------------------------------------
func newHandler(t *Thread, blockFrame *normalCallFrame) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Go creates one goroutine per request, so we also need to create a new Goby thread for every request.
thread := t.vm.newThread()
res := httpResponseClass.initializeInstance()
req := initRequest(t, w, r)
result := thread.builtinMethodYield(blockFrame, req, res)
if err, ok := result.Target.(*Error); ok {
log.Printf("Error: %s", err.message)
res.InstanceVariableSet("@status", t.vm.InitIntegerObject(500))
}
setupResponse(w, r, res)
}
}
func initRequest(t *Thread, w http.ResponseWriter, req *http.Request) *RObject {
r := request{}
reqObj := httpRequestClass.initializeInstance()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return reqObj
}
r.Method = req.Method
r.Protocol = req.Proto
r.Headers = req.Header
r.Body = string(body)
r.ContentLength = req.ContentLength
r.TransferEncoding = req.TransferEncoding
r.Host = req.Host
r.Path = req.URL.Path
r.URL = req.RequestURI
m := structs.Map(r)
for k, v := range m {
varName := "@" + toSnakeCase(k)
reqObj.InstanceVariableSet(varName, t.vm.InitObjectFromGoType(v))
}
vars := map[string]Object{}
for k, v := range mux.Vars(req) {
vars[k] = t.vm.InitStringObject(v)
}
reqObj.InstanceVariableSet("@params", t.vm.InitHashObject(vars))
return reqObj
}
func setupResponse(w http.ResponseWriter, req *http.Request, res *RObject) {
r := &response{}
resStatus, ok := res.InstanceVariableGet("@status")
if ok {
r.status = resStatus.(*IntegerObject).value
} else {
r.status = http.StatusOK
}
resBody, ok := res.InstanceVariableGet("@body")
if !ok {
r.body = ""
} else {
r.body = resBody.(*StringObject).value
}
h, ok := res.InstanceVariableGet("@headers")
if headers, isHashObject := h.(*HashObject); ok && isHashObject {
for k, v := range headers.Pairs {
w.Header().Set(k, v.(*StringObject).value)
}
} else {
r.contentType = "text/plain; charset=utf-8"
w.Header().Set("Content-Type", r.contentType) // normal header
}
w.WriteHeader(r.status)
io.WriteString(w, r.body)
log.Printf("%s %s %s %d\n", req.Method, req.URL.Path, req.Proto, r.status)
}
func toSnakeCase(in string) string {
runes := []rune(in)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}