-
Notifications
You must be signed in to change notification settings - Fork 0
/
pistol.go
203 lines (179 loc) · 5.87 KB
/
pistol.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package Sex
import (
"github.com/Showmax/go-fqdn"
"net/http"
"strings"
)
// Pistol is the Sex HTTP handler, who are used to setup http server
// Example:
// router := Sex.NewPistol().
// Add("/", func(Sex.Request) string {
// return "Hello World"
// }).
// Run()
type Pistol struct {
*http.ServeMux
RootPath string
RouteConfs Dict
Routes Dict
RawRoutes []string
Auth bool
}
// Function thats create a Sex.Pistol and create the init configurations
// Example:
// router := Sex.NewPistol()
func NewPistol() *Pistol {
pistol := new(Pistol)
pistol.ServeMux = http.NewServeMux()
pistol.AddRaw("/", pistol.root, false)
return pistol
}
// Function to Add endpoints to the Sex.Pistol Server
// path are the endpoint location
// route is a void interface thats need to be on next format list:
// - func (http.ResponseWriter, *http.Request)
// - func (Sex.Request) Sex.Response
// (res, status)
// - func (Sex.Request) string // Or (string, int)
// - func (Sex.Request) []byte // Or ([]byte, int)
// - func (Sex.Request) Sex.Json // Or (Sex.Json, int)
// methods are a list of accepted HTTP methods to endpoint
// Example:
// router.Add("/", func(Sex.Request) string {
// return "Hello World"
// }, "POST")
// router.Add("/ok", func(Sex.Request) Sex.Json, int {
// return map[stirng]bool{
// "ok": true,
// }, 404
// })
func (pistol *Pistol) Add(path string, route interface {}, methods ...string) *Pistol {
path = fixPath(path)
root_path := fixPath(pistol.RootPath)
if (path != root_path) {
path = fixPath(root_path + path)
}
path_pattern := GetPathPattern(path)
if len(pistol.RouteConfs) == 0 {
pistol.RouteConfs = make(Dict)
}
if len(pistol.Routes) == 0 {
pistol.Routes = make(Dict)
}
if _, exist := pistol.RouteConfs[path_pattern]; !exist {
pistol.RouteConfs[path_pattern] = make(Prop)
}
conf := Prop{}
conf["path-template"] = path
pistol.RouteConfs[path_pattern] = conf
if methods != nil {
if _, exist := pistol.Routes[path_pattern]; !exist {
pistol.Routes[path_pattern] = make(Prop)
}
for _, method := range methods {
method = strings.ToUpper(method)
pistol.Routes[path_pattern].(Prop)[method] = route
}
} else {
pistol.Routes[path_pattern] = route
}
return pistol
}
// Function to Add golang raw http endpoints to the Sex.Pistol Server
// Example:
// router.AddRaw("/", func(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("Hello World"))
// })
func (pistol *Pistol) AddRaw(path string, f func(http.ResponseWriter, *http.Request), args...interface{}) (*Pistol) {
if pistol.ServeMux == nil {
pistol.ServeMux = http.NewServeMux()
}
var logging bool = true
var methods []string
for _, v := range args {
if method, ok := v.(string); ok {
methods = make([]string, 1)
methods = append(methods, method)
}
if logarg, ok := v.(bool); ok {
logging = logarg
}
}
path = fixPath(path)
pistol.HandleFunc(path, func(w http.ResponseWriter, r *http.Request){
run_request := true
if methods != nil {
run_request = false
for _, m := range methods {
if strings.ToUpper(m) != r.Method {
run_request = true
break
}
}
}
if run_request {
if logging {
Log(r.Method, path, r.URL.RawQuery)
}
f(w, r)
}
})
pistol.RawRoutes = append(pistol.RawRoutes, path)
return pistol
}
// Function to execute de Sex.Pistol server
// Example:
// pistol.Run(5000) // Will run server on port 5000
// pistol.Run("/joao") // will run server on path "/joao"
// pistol.Run("/joao", 80) // will run server on path "/joao" and port 80
// pistol.Run(80, "/joao") // will run server on path "/joao" and port 80
//
// If you run a Sex Pistol server with $SEX_DEBUG setted as "true" thats function will to log list all Sex endpoints of router
func (pistol *Pistol) Run(a ...interface{}) error {
port := 8000
path := "/"
if a != nil {
for _, v := range a {
if ValidateData(v, GenericString) {
path = v.(string)
}
if ValidateData(v, GenericInt) {
port = v.(int)
}
}
}
pistol.RootPath = path
host, err := fqdn.FqdnHostname()
if err != nil {
host = "localhost"
}
msg := Fmt("Running Sex Pistol server at %s:%d%s", host, port, path)
RawLog("\033[32;1m[info] \033[00m", false, msg)
if GetEnv("SEX_DEBUG", "false") != "false" {
for path, methods := range pistol.Routes {
methods_str := ""
if methods, ok := methods.(Prop); ok {
for method := range methods {
methods_str += Fmt("%s ", method)
}
} else {
methods_str = "ALL METHODS"
}
msg := Fmt("%s <- %s", pistol.RouteConfs[path].(Prop)["path-template"], methods_str)
RawLog("\033[32;1m[info] \033[00m", false, msg)
}
for _, path := range pistol.RawRoutes {
msg := Fmt("%s <- %s", path, "ALL METHODS")
RawLog("\033[32;1m[info] \033[00m", false, msg)
}
}
var handler http.Handler = pistol
if a != nil {
for _, v := range a {
if config, ok := v.(func (h http.Handler) http.Handler); ok {
handler = config(handler)
}
}
}
return http.ListenAndServe(Fmt(":%d", port), handler)
}