-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_cache.go
More file actions
39 lines (34 loc) · 1.06 KB
/
Copy pathfetch_cache.go
File metadata and controls
39 lines (34 loc) · 1.06 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
package tools
import (
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
)
// fetchCacheDir returns the configured disk cache directory for fetched URLs, or
// "" when caching is disabled (the default).
func fetchCacheDir() string {
return os.Getenv("GOPHERMIND_FETCH_CACHE_DIR")
}
// cacheKeyPath maps a URL to its cache file path under dir.
func cacheKeyPath(dir, url string) string {
sum := sha256.Sum256([]byte(url))
return filepath.Join(dir, hex.EncodeToString(sum[:])+".txt")
}
// cacheGet returns a previously cached fetch result for url, if present. This is
// what lets fetched docs be reused offline.
func cacheGet(dir, url string) (string, bool) {
data, err := os.ReadFile(cacheKeyPath(dir, url))
if err != nil {
return "", false
}
return string(data), true
}
// cachePut stores a fetch result for url, best-effort (errors are ignored so a
// caching failure never breaks a fetch).
func cachePut(dir, url, content string) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return
}
_ = os.WriteFile(cacheKeyPath(dir, url), []byte(content), 0o644)
}