This repository was archived by the owner on May 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
87 lines (71 loc) · 1.58 KB
/
cache.go
File metadata and controls
87 lines (71 loc) · 1.58 KB
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
/*
* Copyright (c) 2021-2023 Mikhail Knyazhev <markus621@gmail.com>. All rights reserved.
* Use of this source code is governed by a BSD-3-Clause license that can be found in the LICENSE file.
*/
package static
import (
"net/http"
"sort"
"sync"
)
type Reader interface {
Get(filename string) ([]byte, string)
List() []string
ResponseWrite(w http.ResponseWriter, filename string) error
}
// Cache model
type Cache struct {
files map[string][]byte
mux sync.RWMutex
}
// New init cache
func New() *Cache {
c := &Cache{}
c.Reset()
return c
}
// Reset clean cache
func (c *Cache) Reset() {
c.mux.Lock()
defer c.mux.Unlock()
c.files = make(map[string][]byte)
}
// Set setting data to cache
func (c *Cache) Set(filename string, v []byte) {
c.mux.Lock()
defer c.mux.Unlock()
c.files[filename] = v
}
// Get getting file by name
func (c *Cache) Get(filename string) ([]byte, string) {
c.mux.RLock()
defer c.mux.RUnlock()
b, ok := c.files[filename]
if !ok {
return nil, ""
}
return b, DetectContentType(filename, b)
}
// ResponseWrite write file to response
func (c *Cache) ResponseWrite(w http.ResponseWriter, filename string) error {
b, ct := c.Get(filename)
if b == nil {
w.WriteHeader(http.StatusNotFound)
return nil
}
w.Header().Set("Content-Type", ct)
w.WriteHeader(http.StatusOK)
_, err := w.Write(b)
return err
}
// List getting all files list
func (c *Cache) List() []string {
c.mux.RLock()
defer c.mux.RUnlock()
result := make([]string, 0, len(c.files))
for name := range c.files {
result = append(result, name)
}
sort.Strings(result)
return result
}