forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
244 lines (200 loc) · 5.25 KB
/
utils.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package gserv
import (
"bytes"
"crypto/tls"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/alpineiq/gserv/internal"
"golang.org/x/net/http2"
)
var nukeCookieDate = time.Date(1991, time.August, 6, 0, 0, 0, 0, time.UTC)
// HTTPHandler returns a Handler from an http.Handler.
func HTTPHandler(h http.Handler) Handler {
return HTTPHandlerFunc(h.ServeHTTP)
}
// FromHTTPHandlerFunc returns a Handler from an http.Handler.
func HTTPHandlerFunc(h http.HandlerFunc) Handler {
return func(ctx *Context) Response {
h(ctx, ctx.Req)
return nil
}
}
// StaticDirStd is a QoL wrapper for http.FileServer(http.Dir(dir)).
func StaticDirStd(prefix, dir string, allowListing bool) Handler {
var fs http.FileSystem
if allowListing {
fs = http.Dir(dir)
} else {
fs = noListingDir(dir)
}
return HTTPHandler(http.StripPrefix(prefix, http.FileServer(fs)))
}
// StaticDir is a shorthand for StaticDirWithLimit(dir, paramName, -1).
func StaticDir(dir, paramName string) Handler {
return StaticDirStd("", dir, false)
// return StaticDirWithLimit(dir, paramName, -1)
}
// StaticDirWithLimit returns a handler that handles serving static files.
// paramName is the path param, for example: s.GET("/s/*fp", StaticDirWithLimit("./static/", "fp", 1000)).
// if limit is > 0, it will only ever serve N files at a time.
// BUG: returns 0 size for some reason
func StaticDirWithLimit(dir, paramName string, limit int) Handler {
var (
sem chan struct{}
e struct{}
)
if limit > 0 {
sem = make(chan struct{}, limit)
}
return func(ctx *Context) Response {
path := ctx.Param(paramName)
if sem != nil {
sem <- e
defer func() { <-sem }()
}
if err := ctx.File(filepath.Join(dir, path)); err != nil {
if os.IsNotExist(err) {
http.Error(ctx, "file not found", http.StatusNotFound)
return nil
}
http.Error(ctx, err.Error(), http.StatusInternalServerError)
}
return nil
}
}
type noListingDir string
func (d noListingDir) Open(name string) (f http.File, err error) {
const indexName = "/index.html"
hd := http.Dir(d)
if f, err = hd.Open(name); err != nil {
return
}
if s, _ := f.Stat(); s != nil && s.IsDir() {
f.Close()
index := strings.TrimSuffix(name, "/") + "/index.html"
return hd.Open(index)
}
return
}
// AllowCORS allows CORS responses.
// If methods is empty, it will respond with the requested method.
// If headers is empty, it will respond with the requested headers.
// If origins is empty, it will respond with the requested origin.
// will automatically install an OPTIONS handler to each passed group.
func AllowCORS(methods, headers, origins []string, groups ...GroupType) Handler {
ms := strings.Join(methods, ", ")
hs := strings.Join(headers, ", ")
om := map[string]bool{}
for _, orig := range origins {
om[orig] = true
}
fn := func(ctx *Context) (_ Response) {
rh, wh := ctx.Req.Header, ctx.Header()
origin := rh.Get("Origin")
if origin == "" { // return early if it's not a browser request
return
}
if len(om) == 0 || om[origin] {
wh.Set("Access-Control-Allow-Origin", origin)
wh.Set("Access-Control-Allow-Credentials", "true")
} else {
return
}
if len(ms) > 0 {
wh.Set("Access-Control-Allow-Methods", ms)
} else if rm := rh.Get("Access-Control-Request-Method"); rm != "" {
wh.Set("Access-Control-Allow-Methods", rm)
}
if len(hs) > 0 {
wh.Set("Access-Control-Allow-Headers", hs)
} else if rh := rh.Get("Access-Control-Request-Headers"); rh != "" {
wh.Set("Access-Control-Allow-Headers", rh)
}
wh.Set("Access-Control-Max-Age", "86400") // 24 hours
return
}
for _, g := range groups {
g.AddRoute("OPTIONS", "/*x", fn)
}
return fn
}
type M map[string]any
// ToJSON returns a string json representation of M, mostly for debugging.
func (m M) ToJSON(indent bool) string {
if len(m) == 0 {
return "{}"
}
var j []byte
if indent {
j, _ = internal.MarshalIndent(m)
} else {
j, _ = internal.Marshal(m)
}
return string(j)
}
// MultiError handles returning multiple errors.
type MultiError []error
// Push adds an error to the MultiError slice if err != nil.
func (me *MultiError) Push(err error) {
if err != nil {
*me = append(*me, err)
}
}
// Err returns nil if me is empty.
func (me MultiError) Err() error {
if len(me) == 0 {
return nil
}
if len(me) == 1 {
return me[0]
}
return me
}
func (me MultiError) Error() string {
errs := make([]string, 0, len(me))
for _, err := range me {
errs = append(errs, err.Error())
}
return "multiple errors returned:\n\t" + strings.Join(errs, "\n\t")
}
func H2Client() *http.Client {
return &http.Client{
Transport: &http2.Transport{
AllowHTTP: true,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
},
}
}
type DummyResponseWriter struct {
h http.Header
buf bytes.Buffer
st int
}
func (d *DummyResponseWriter) Header() http.Header {
if d.h == nil {
d.h = make(http.Header)
}
return d.h
}
func (d *DummyResponseWriter) Write(b []byte) (int, error) {
if d.buf.Len() == 0 {
d.WriteHeader(200)
}
return d.buf.Write(b)
}
func (d *DummyResponseWriter) WriteHeader(v int) {
d.st = v
d.h.Write(&d.buf)
}
func (d *DummyResponseWriter) Status() int {
return d.st
}
func (d *DummyResponseWriter) Bytes() []byte {
return d.buf.Bytes()
}