-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsun.go
109 lines (99 loc) · 1.92 KB
/
sun.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
package sun
import (
"fmt"
"net/http"
"sync"
)
//Context
type Context struct {
sunspot *Sunspot
}
//End Context
type Sunspot struct {
tree *node
pool sync.Pool
}
func New() *Sunspot {
sunspot := &Sunspot{tree: new(node)}
sunspot.pool.New = func() interface{} {
return sunspot.allocateContext()
}
return sunspot
}
func MethodNotAllowed(w http.ResponseWriter, r *http.Request) {
http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed)
}
func (sunspot *Sunspot) allocateContext() *Context {
return &Context{sunspot: sunspot}
}
func (sunspot *Sunspot) Handle(path string, handle interface{}) {
sunspot.tree.addRoute(path, handle)
}
func (sunspot *Sunspot) Run(addr ...string) (err error) {
address := resolveAddress(addr)
err = http.ListenAndServe(address, sunspot)
return
}
// ServeHTTP conforms to the http.Handler interface.
func (sunspot *Sunspot) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := sunspot.pool.Get().(*Context)
c.writermem.reset(w)
c.Request = req
c.reset()
path := r.URL.Path
handle, ps, _ := sunspot.tree.getValue(path)
if handle != nil {
switch r.Method {
case "OPTIONS":
h, ok := handle.(OptionsHandle)
if ok {
h.Options(w, r, ps)
return
}
case "GET":
h, ok := handle.(GetHandle)
if ok {
h.Get(w, r, ps)
return
}
case "HEAD":
h, ok := handle.(HeadHandle)
if ok {
h.Head(w, r, ps)
return
}
case "POST":
h, ok := handle.(PostHandle)
if ok {
h.Post(w, r, ps)
return
}
case "PUT":
h, ok := handle.(PutHandle)
if ok {
h.Put(w, r, ps)
return
}
case "DELETE":
h, ok := handle.(DeleteHandle)
if ok {
h.Delete(w, r, ps)
return
}
case "TRACE":
h, ok := handle.(TraceHandle)
if ok {
h.Trace(w, r, ps)
return
}
case "CONNECT":
fmt.Println("CONNECT")
default:
fmt.Println("default")
}
MethodNotAllowed(w, r)
return
}
http.NotFound(w, r)
return
}