Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/cache/cache.go
3431 views
1
package cache
2
3
import (
4
"crypto/sha256"
5
"encoding/hex"
6
"encoding/json"
7
"time"
8
)
9
10
type Cache struct {
11
store Store
12
}
13
14
func New(store Store) *Cache {
15
return &Cache{
16
store: store,
17
}
18
}
19
20
func (c *Cache) GetSessionID(endpoint string) (string, error) {
21
key := hash(endpoint)
22
raw, err := c.store.Get(key)
23
if err != nil {
24
return "", err
25
}
26
27
var entry Entry
28
if err := json.Unmarshal(raw, &entry); err != nil {
29
return "", err
30
}
31
32
return entry.SessionID, nil
33
}
34
35
func (c *Cache) SetSessionID(endpoint string, sessionId string) error {
36
key := hash(endpoint)
37
38
entry := Entry{
39
Endpoint: endpoint,
40
SessionID: sessionId,
41
UpdatedAt: time.Now(),
42
}
43
44
bytes, err := json.Marshal(entry)
45
if err != nil {
46
return err
47
}
48
49
return c.store.Set(key, bytes)
50
}
51
52
func (c *Cache) DeleteSessionID(endpoint string) error {
53
key := hash(endpoint)
54
return c.store.Delete(key)
55
}
56
57
func hash(endpoint string) string {
58
sum := sha256.Sum256([]byte(endpoint))
59
return hex.EncodeToString(sum[:])
60
}
61
62