@@ -15,6 +15,13 @@ type Route struct {
15
15
Middlewares []func (http.ResponseWriter , * http.Request ) bool
16
16
}
17
17
18
+ type StaticRoute struct {
19
+ RoutePrefix string
20
+ StaticDir string
21
+ }
22
+
23
+ var staticRoutes []StaticRoute
24
+
18
25
var registerRoutes []Route
19
26
20
27
func CreateServerBuiltin () * object.Builtin {
@@ -30,8 +37,13 @@ func CreateServerBuiltin() *object.Builtin {
30
37
return NewError ("argument to `server` must be INTEGER, got %s" , args [0 ].Type ())
31
38
}
32
39
40
+ for _ , sr := range staticRoutes {
41
+ http .Handle (sr .RoutePrefix + "/" , http .StripPrefix (sr .RoutePrefix , http .FileServer (http .Dir (sr .StaticDir ))))
42
+ }
43
+
33
44
http .HandleFunc ("/" , func (w http.ResponseWriter , r * http.Request ) {
34
45
route := matchRoute (r )
46
+
35
47
if route == nil {
36
48
http .NotFound (w , r )
37
49
return
@@ -182,6 +194,30 @@ func HtmlHandlerBuiltin() *object.Builtin {
182
194
}
183
195
}
184
196
197
+ func ServerStaticBuiltin () * object.Builtin {
198
+ return & object.Builtin {
199
+ Fn : func (args ... object.Object ) object.Object {
200
+ if len (args ) != 2 {
201
+ return NewError ("wrong number of arguments. got=%d, want=2" , len (args ))
202
+ }
203
+
204
+ prefix , ok1 := args [0 ].(* object.String )
205
+ dir , ok2 := args [1 ].(* object.String )
206
+
207
+ if ! ok1 || ! ok2 {
208
+ return NewError ("method and path must be STRING" )
209
+ }
210
+
211
+ staticRoutes = append (staticRoutes , StaticRoute {
212
+ RoutePrefix : prefix .Value ,
213
+ StaticDir : dir .Value ,
214
+ })
215
+
216
+ return nil
217
+ },
218
+ }
219
+ }
220
+
185
221
func matchRoute (r * http.Request ) * Route {
186
222
for _ , route := range registerRoutes {
187
223
if route .Method != r .Method {
0 commit comments