-
Notifications
You must be signed in to change notification settings - Fork 1
/
staticservermiddleware.go
42 lines (36 loc) · 1.13 KB
/
staticservermiddleware.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
package soggy
import (
"net/http"
"path/filepath"
"strings"
"os"
)
type StaticServerMiddleware struct {
path string
}
func (staticServer *StaticServerMiddleware) GetRelativeFilePath(urlPath string) string {
if staticServer.path == "/" {
return urlPath
}
return urlPath[len(staticServer.path)-1:len(urlPath)]
}
func (staticServer *StaticServerMiddleware) IsValidForPath(path string) bool {
return strings.HasPrefix(path, staticServer.path)
}
func (staticServer *StaticServerMiddleware) Execute(ctx *Context) {
req := ctx.Req
if (req.Method == GET_METHOD || req.Method == HEAD_METHOD) && staticServer.IsValidForPath(req.RelativePath) {
staticPath := ctx.Server.Config[CONFIG_STATIC_PATH].(string)
staticFile := filepath.Join(staticPath, staticServer.GetRelativeFilePath(req.RelativePath))
if stat, err := os.Stat(staticFile); err == nil && !stat.IsDir() {
http.ServeFile(ctx.Res, req.Request, staticFile)
} else {
ctx.Next(nil)
}
} else {
ctx.Next(nil)
}
}
func NewStaticServerMiddleware(path string) *StaticServerMiddleware {
return &StaticServerMiddleware{ SaneURLPath(path) }
}