-
Notifications
You must be signed in to change notification settings - Fork 2
/
static.go
78 lines (65 loc) · 1.48 KB
/
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
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
// Based on https://github.com/martini-contrib/staticbin
package staticbin
import (
"bytes"
"log"
"net/http"
"path"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type Options struct {
// SkipLogging will disable [Static] log messages when a static file is served.
SkipLogging bool
// IndexFile defines which file to serve as index if it exists.
IndexFile string
// Path prefix
Dir string
}
func (o *Options) init() {
if o.IndexFile == "" {
o.IndexFile = "index.html"
}
}
// Static returns a middleware handler that serves static files in the given directory.
func Static(asset func(string) ([]byte, error), options ...Options) gin.HandlerFunc {
if asset == nil {
panic("asset is nil")
}
opt := Options{}
for _, o := range options {
opt = o
break
}
opt.init()
modtime := time.Now()
return func(c *gin.Context) {
if c.Request.Method != "GET" && c.Request.Method != "HEAD" {
// Request is not correct. Go farther.
return
}
url := c.Request.URL.Path
if !strings.HasPrefix(url, opt.Dir) {
return
}
file := strings.TrimPrefix(
strings.TrimPrefix(url, opt.Dir),
"/",
)
b, err := asset(file)
if err != nil {
// Try to serve the index file.
b, err = asset(path.Join(file, opt.IndexFile))
if err != nil {
// Go farther if the asset could not be found.
return
}
}
if !opt.SkipLogging {
log.Println("[Static] Serving " + url)
}
http.ServeContent(c.Writer, c.Request, url, modtime, bytes.NewReader(b))
c.Abort()
}
}