/
runtime.go
41 lines (33 loc) · 927 Bytes
/
runtime.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
package gendry
import "io"
import "strings"
import "net/http"
// Runtime defines an interface that is used as the http runtime for the gendry api.
type Runtime interface {
Start(string, chan<- error)
}
// NewRuntime returns an initialized runtime using the provided route list.
func NewRuntime(routes *RouteList, log LeveledLogger) Runtime {
r := &runtime{
LeveledLogger: log,
routes: routes,
}
return r
}
type runtime struct {
LeveledLogger
routes *RouteList
}
func (r *runtime) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
route, params, found := r.routes.Match(request)
if !found {
r.Debugf("not found: %v", request.URL)
responseWriter.WriteHeader(404)
io.Copy(responseWriter, strings.NewReader("not-found"))
return
}
route(responseWriter, request, params)
}
func (r *runtime) Start(addr string, closed chan<- error) {
closed <- http.ListenAndServe(addr, r)
}