/
static.go
43 lines (37 loc) · 915 Bytes
/
static.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
package cosweb
import (
"fmt"
"github.com/hwclegend/cosgo/app"
"net/http"
"path"
"path/filepath"
"strings"
)
const iStaticRoutePath = "_StaticRoutePath"
type Static struct {
root string
}
func NewStatic(root string) *Static {
if !path.IsAbs(root) {
root = filepath.Join(app.Config.GetString("appWorkDir"), root)
}
return &Static{root: root}
}
func (this *Static) Route(s *Server, prefix string, method ...string) {
arr := []string{strings.TrimSuffix(prefix, "/"), "*" + iStaticRoutePath}
route := strings.Join(arr, "/")
s.Register(route, this.handle, method...)
}
func (this *Static) handle(c *Context) error {
name := c.Get(iStaticRoutePath, RequestDataTypeParam)
if name == "" {
return nil
}
file := filepath.Join(this.root, name)
if !strings.HasPrefix(file, this.root) {
return nil
}
fmt.Printf("static file:%v\n", file)
http.ServeFile(c.Response, c.Request, file)
return nil
}