forked from beatgammit/artichoke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
186 lines (156 loc) · 4.22 KB
/
core.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
package artichoke
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"path"
"strconv"
)
var errors = map[int]string{
http.StatusNotFound: fmt.Sprintf("<h1>Error %d: Not Found</h1><br /><br />The page or resource requested could not be found. If this was a link or worked previously, please notify your webmaster.", http.StatusNotFound),
http.StatusInternalServerError: fmt.Sprintf("<h1>Error %d: Internal Server Error</h1><br /><br />An internal server error prevented execution of this request. Please notify the webmaster.", http.StatusInternalServerError),
}
type Data interface {
Get(string) (interface{}, bool)
GetString(string) string
Set(string, interface{})
}
type data struct {
raw map[string]interface{}
}
func (d *data) Get(key string) (interface{}, bool) {
i, ok := d.raw[key]
return i, ok
}
func (d *data) GetString(key string) string {
i, ok := d.raw[key]
if !ok {
return ""
}
if s, ok := i.(string); ok {
return s
}
return ""
}
func (d *data) Set(key string, val interface{}) {
d.raw[key] = val
}
// once a middleware returns true, no more middleware will be executed
//
// the last parameter is a general-purpose map passed to each middleware
// middleware can use this to pass arbitrary data down the stack
type Middleware func(http.ResponseWriter, *http.Request, Data) bool
type Server struct {
handler func(http.ResponseWriter, *http.Request)
middleware []Middleware
l net.Listener
// for TLS connections
certFile string
keyFile string
}
var server Server
// create a new server with the options provided
// the first parameter specifies options to control behavior of the server
// any other parameters are just passed to Use for convenience
func New(options map[string]interface{}, fns ...Middleware) *Server {
s := Server{}
s.Use(fns...)
return &s
}
// Adds any number of middleware
// fns is any number of functions that act as middleware
// they will be called order on every request
func (s *Server) Use(fns ...Middleware) {
s.middleware = append(s.middleware, fns...)
}
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "CONNECT" {
p := cleanPath(r.URL.Path)
if p != r.URL.Path {
if "/"+p == r.URL.Path {
// fixup path
r.URL.Path = p
} else {
// return 301
url := *r.URL
url.Path = p
h := http.RedirectHandler(url.String(), http.StatusMovedPermanently)
h.ServeHTTP(w, r)
return
}
}
}
data := new(data)
data.raw = make(map[string]interface{})
for _, fn := range s.middleware {
if fn(w, r, data) == true {
return
}
}
status := http.StatusNotFound
fmt.Println("No handler for this request:")
fmt.Printf(" Method: %s\n", r.Method)
fmt.Printf(" URL: %s\n", r.URL.Path)
fmt.Println(" Headers:")
for k, v := range r.Header {
fmt.Printf(" %s: %s\n", k, v)
}
fmt.Println("")
resp := errors[status]
w.Header().Add("Content-Type", "text/html")
w.Header().Add("Content-Length", strconv.Itoa(len(resp)))
w.WriteHeader(status)
// for HEAD requests, do everything except the body
if r.Method == "HEAD" {
w.Write([]byte(""))
return
}
w.Write([]byte(resp))
}
func (s *Server) Run(host string, port int) {
addr := fmt.Sprintf("%s:%d", host, port)
l, e := net.Listen("tcp", addr)
if e != nil {
panic(e)
}
s.l = l
srv := &http.Server{Addr: addr, Handler: s}
fmt.Println("Server starting on port:", port)
srv.Serve(s.l)
}
func (s *Server) RunTLS(host string, port int, certFile string, keyFile string) {
addr := fmt.Sprintf("%s:%d", host, port)
l, err := net.Listen("tcp", addr)
if err != nil {
panic(err)
}
config := &tls.Config{NextProtos: []string{"http/1.1"}}
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
panic(err)
}
s.l = l
srv := &http.Server{Addr: addr, Handler: s, TLSConfig: config}
fmt.Println("Secure server starting on port:", port)
srv.Serve(s.l)
}
func (s *Server) Stop() {
s.l.Close()
}