-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
88 lines (75 loc) · 2.01 KB
/
serve.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
package bstore
import (
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/cartersusi/bstore/pkg/fops"
"github.com/gin-gonic/gin"
)
func (bstore *ServerCfg) Serve() gin.HandlerFunc {
return func(c *gin.Context) {
// no rw priv needed for public files
log.Println("Valid Serve Request for", c.Request.URL.Path)
path := strings.Replace(c.Request.URL.Path, "bstore", bstore.PublicBasePath, 1)
if !strings.HasPrefix(path, "/"+bstore.PublicBasePath) {
c.Next()
return
}
fpath := filepath.Join(bstore.PublicBasePath, strings.TrimPrefix(path, "/"+bstore.PublicBasePath))
isCompressed := true
info, err := os.Stat(fpath)
if err == nil {
if !info.IsDir() {
isCompressed = false
}
}
cached_content, ok := check_OR_get(c, fpath)
if ok {
contentType := http.DetectContentType(cached_content)
c.Header("Content-Type", contentType)
c.Data(http.StatusOK, contentType, cached_content)
return
}
if isCompressed {
fpath = fpath + ".zst"
}
if isCompressed {
content, err := fops.Decompress(fpath, bstore.Encrypt)
if err != nil {
HandleError(c, NewError(http.StatusInternalServerError, "Error decompressing file", err))
return
}
set_cache(c, strings.TrimSuffix(fpath, ".zst"), content)
contentType := http.DetectContentType(content)
c.Header("Content-Type", contentType)
c.Data(http.StatusOK, contentType, content)
} else {
file, err := os.Open(fpath)
if err != nil {
HandleError(c, NewError(http.StatusNotFound, "File not found", err))
return
}
defer file.Close()
http.ServeContent(c.Writer, c.Request, info.Name(), info.ModTime(), file)
}
}
}
func check_OR_get(c *gin.Context, key string) ([]byte, bool) {
cache := GetCache(c)
if cache != nil {
if val, ok := cache.Get(key); ok {
log.Println("Cache hit for", key)
return val, true
}
}
return nil, false
}
func set_cache(c *gin.Context, key string, val []byte) {
cache := GetCache(c)
if cache != nil {
log.Println("Caching", key)
cache.Add(key, val)
}
}