-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot.go
81 lines (66 loc) · 1.97 KB
/
root.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
package Sex
import (
"os"
re "regexp"
"net/http"
)
// Function to make Sex.Pistol a http.Handler
func (pistol *Pistol) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if pistol == nil || pistol.ServeMux == nil {
pistol = NewPistol()
}
for _, plugin := range pistol.plugins {
w, r = plugin.Root(w, r)
}
pistol.ServeMux.ServeHTTP(w, r)
}
// root endpoint to run all Sex endpoints
func (pistol *Pistol) root(w http.ResponseWriter, r *http.Request) {
request := NewRequest()
request.Request = *r
path := r.URL.Path
path = fixPath(r.URL.Path)
root_path := fixPath(pistol.rootPath)
if root_path == "/" {
root_path = ""
}
response_log_message := Fmt("%s %s %s ", r.Method, path, r.URL.RawQuery)
for path_pattern, route := range pistol.routes {
path_regex := re.MustCompile("^" + root_path + path_pattern + `{1}`)
conf := pistol.config[path_pattern]
isMatching := path_regex.MatchString(path)
if os.Getenv("SEX_DEBUG") == "true" {
RawLog(LogLevelInfo, false, Fmt(`"%s" is "%s" ? %v`, path_pattern, path, isMatching))
}
if isMatching {
request.Conf = conf
request.PathVars, _ = GetPathVars(conf.Get("path-template"), path)
methods_allowed := conf.Values("methods-allowed")
if len(methods_allowed) > 0 && IndexOf(request.Method, methods_allowed) < 0 {
st := StatusMethodNotAllowed
msg := StatusText(st)
http.Error(w, msg, st)
RawLog(LogLevelError, false,
response_log_message+Fmt("%d: %s", st, msg))
return
}
response := NewResponse()
response.ResponseWriter = w
if err := runRoute(route, *response, *request); err != nil {
st := response.Status
msg := StatusText(st)
if len(response.Body) == 0 {
msg = string(response.Body)
}
RawLog(LogLevelError, false, response_log_message+Fmt("%d: %s", st, msg))
http.Error(w, msg, st)
}
return
}
}
st := StatusNotFound
msg := StatusText(st)
http.Error(w, msg, st)
RawLog(LogLevelError, false,
response_log_message+Fmt("%d: %s", st, msg))
}