forked from EverythingMe/httpcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
65 lines (53 loc) · 1.33 KB
/
file.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
package httpcache
import (
"encoding/gob"
"log"
"net/url"
"os"
"path"
"strings"
)
// A fileCache implements a cache with files saved in Path.
// It is not safe for concurrency.
type fileCache struct {
Path string
}
// Windows does not accept `\/:*?"<>|` and UNIX `/`, replace all with dash.
var fileNameReplacer = strings.NewReplacer(`/`, `-`, `\`, `-`, `:`, `-`, `*`,
`-`, `?`, `-`, `"`, `-`, `<`, `-`, `>`, `-`, `|`, `-`)
// fileName builds a file name from an URL to be used as cache.
func (f fileCache) fileName(u *url.URL) string {
return path.Join(f.Path, fileNameReplacer.Replace(u.String()))
}
// Get gets data saved for an URL if present in cache.
func (f fileCache) Get(u *url.URL) (*Entry, error) {
fp, err := os.Open(f.fileName(u))
if err != nil {
log.Println("Could not open ", u)
return nil, err
}
decoder := gob.NewDecoder(fp)
defer fp.Close()
var e Entry
err = decoder.Decode(&e)
if err != nil {
log.Printf("Could not decode %s: %s\n", u, err)
return nil, err
}
return &e, nil
}
// Put puts data of an URL in cache.
func (f fileCache) Put(u *url.URL, e *Entry) error {
fp, err := os.Create(f.fileName(u))
if err != nil {
return err
}
defer fp.Close()
encoder := gob.NewEncoder(fp)
err = encoder.Encode(*e)
if err != nil {
log.Println("Could not write to cache: ", err)
return err
}
return nil
}