-
Notifications
You must be signed in to change notification settings - Fork 171
/
simple_server.go
196 lines (159 loc) · 4.35 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
package vm
import (
"github.com/goby-lang/goby/Godeps/_workspace/src/github.com/fatih/structs"
"github.com/goby-lang/goby/Godeps/_workspace/src/github.com/gorilla/mux"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
)
type response struct {
status int
body string
contentType string
}
type request struct {
Method string
Body string
URL string
Path string
Host string
}
func initializeSimpleServerClass(vm *VM) {
initializeHTTPClass(vm)
net := vm.loadConstant("Net", true)
simpleServer := initializeClass("SimpleServer", false)
simpleServer.setBuiltInMethods(builtinSimpleServerInstanceMethods(), false)
net.constants[simpleServer.Name] = &Pointer{simpleServer}
vm.execGobyLib("net/simple_server.gb")
}
func builtinSimpleServerInstanceMethods() []*BuiltInMethodObject {
router := mux.NewRouter()
return []*BuiltInMethodObject{
{Name: "start",
Fn: func(receiver Object) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *callFrame) Object {
var port string
var serveStatic bool
server := receiver.(*RObject)
portVar, ok := server.InstanceVariables.get("@port")
if !ok {
port = "8080"
} else {
port = portVar.(*StringObject).Value
}
fileRoot, serveStatic := server.InstanceVariables.get("@file_root")
if serveStatic {
fr := fileRoot.(*StringObject).Value
currentDir, _ := os.Getwd()
fp := filepath.Join(currentDir, fr)
fs := http.FileServer(http.Dir(fp))
http.Handle("/", fs)
}
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)
}
}()
router.PathPrefix("/").Handler(http.FileServer(http.Dir(t.vm.fileDir)))
http.Handle("/", router)
err := http.ListenAndServe(":"+port, nil)
if err != http.ErrServerClosed { // HL
log.Fatalf("listen: %s\n", err)
}
return receiver
}
},
},
{
Name: "mount",
Fn: func(receiver Object) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *callFrame) Object {
path := args[0].(*StringObject).Value
router.HandleFunc(path, newHandler(t, blockFrame))
return receiver
}
},
},
}
}
func newHandler(t *thread, blockFrame *callFrame) 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(w, r)
thread.builtInMethodYield(blockFrame, req, res)
thread = nil
setupResponse(w, r, res)
}
}
func initRequest(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.Body = string(body)
r.Path = req.URL.Path
r.URL = req.RequestURI
r.Host = req.Host
m := structs.Map(r)
for k, v := range m {
varName := "@" + strings.ToLower(k)
reqObj.InstanceVariables.set(varName, initObject(v))
}
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
}
contentType, ok := res.instanceVariableGet("@content_type")
if !ok {
r.contentType = "text/plain; charset=utf-8"
} else {
r.contentType = contentType.toString()
}
w.WriteHeader(r.status)
w.Header().Set("Content-Type", r.contentType) // normal header
io.WriteString(w, r.body)
log.Printf("%s %s %s %d\n", req.Method, req.URL.Path, req.Proto, r.status)
}
func initObject(v interface{}) Object {
switch v := v.(type) {
case string:
return initStringObject(v)
case int:
return initilaizeInteger(v)
case bool:
if v {
return TRUE
}
return FALSE
default:
panic("Can't init object")
}
}