-
Notifications
You must be signed in to change notification settings - Fork 0
/
slid.go
48 lines (39 loc) · 884 Bytes
/
slid.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
package slid
import (
"fmt"
"net/http"
)
const (
GET = "GET"
)
type Slid struct {
Router *Router
Config *Config
}
func New(cfg *Config) *Slid {
return &Slid{
Router: new(Router),
Config: cfg,
}
}
func (s *Slid) Get(path string, handler func(*Context)) {
s.Router.routes = append(s.Router.routes, Route{"GET", path, handler})
}
func (s *Slid) GetFile(path, filename string) {
s.Router.routes = append(s.Router.routes, Route{"GET", path, func(c *Context) {
c.Serve(filename)
}})
}
func (s *Slid) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := NewContext(r, w, s)
for _, route := range s.Router.Routes() {
if route.Path == r.URL.String() && route.Method == r.Method {
route.Handler(ctx)
}
}
}
func (s *Slid) Run(callback func()) {
addr := fmt.Sprintf("localhost:%d", s.Config.Port)
callback()
fmt.Println(http.ListenAndServe(addr, s))
}