/
fasthttp.go
50 lines (42 loc) · 1.17 KB
/
fasthttp.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
package brfasthttp
import (
"io"
"github.com/valyala/fasthttp"
"go.pyspa.org/brbundle"
"go.pyspa.org/brbundle/websupport"
)
func Mount(option ...brbundle.WebOption) fasthttp.RequestHandler {
o := websupport.InitOption(option)
return func (ctx *fasthttp.RequestCtx) {
p, ok := ctx.UserValue("filepath").(string)
if !ok {
p = string(ctx.Path())
}
file, found, redirectDir := websupport.FindFile(p, o)
if redirectDir {
ctx.Redirect("./", fasthttp.StatusFound)
return
} else if !found {
ctx.SetStatusCode(fasthttp.StatusNotFound)
return
}
reader, etag, headers, err := websupport.GetContent(file, o, string(ctx.Request.Header.Peek("Accept-Encoding")))
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
}
defer reader.Close()
for _, header := range headers {
ctx.Response.Header.Set(header[0], header[1])
}
if string(ctx.Request.Header.Peek("If-None-Match")) == etag {
ctx.SetStatusCode(fasthttp.StatusNotModified)
return
} else {
defer reader.Close()
io.Copy(ctx, reader)
}
}
}
func MountRouter(option ...brbundle.WebOption) (string, fasthttp.RequestHandler) {
return "/*filepath", Mount(option...)
}