-
Notifications
You must be signed in to change notification settings - Fork 0
/
cached_client.go
79 lines (67 loc) · 1.42 KB
/
cached_client.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
package cbrates
import (
"context"
"encoding/gob"
"log"
"os"
"path"
"time"
)
type cachedClient struct {
logger *log.Logger
client Client
cachePath string
}
func (c *cachedClient) GetDailyRates(ctx context.Context, year int, month time.Month, day int) (*ValCurs, error) {
if time.Date(year, month, day, 0, 0, 0, 0, time.UTC).After(time.Now()) {
return c.client.GetDailyRates(ctx, year, month, day)
}
key := path.Join(c.cachePath, "GetDailyRates-"+formatDate(year, month, day))
if result := func() *ValCurs {
f, err := os.Open(key)
if err != nil {
if !os.IsNotExist(err) {
c.logger.Println(err)
}
return nil
}
defer f.Close()
var result ValCurs
decoder := gob.NewDecoder(f)
if err := decoder.Decode(&result); err != nil {
c.logger.Println(err)
return nil
}
return &result
}(); result != nil {
return result, nil
}
result, err := c.client.GetDailyRates(ctx, year, month, day)
if err != nil {
return nil, err
}
func() {
f, err := os.CreateTemp(c.cachePath, "tmpcache")
if err != nil {
c.logger.Println(err)
return
}
name := f.Name()
defer f.Close()
encoder := gob.NewEncoder(f)
if err := encoder.Encode(result); err != nil {
c.logger.Println(err)
return
}
if err := f.Close(); err != nil {
c.logger.Println(err)
return
}
f = nil
if err := os.Rename(name, key); err != nil {
c.logger.Println(err)
return
}
}()
return result, nil
}