Blob


1 package lemmy
3 import (
4 "fmt"
5 "net/http"
6 "strconv"
7 "strings"
8 "sync"
9 "time"
10 )
12 type cache struct {
13 post map[int]entry
14 community map[string]entry
15 mu *sync.Mutex
16 }
18 type entry struct {
19 post Post
20 community Community
21 expiry time.Time
22 }
24 func (c *cache) store(p Post, com Community, dur time.Duration) {
25 c.mu.Lock()
26 defer c.mu.Unlock()
27 t := time.Now().Add(dur)
28 entry := entry{expiry: t}
29 if p.Name() != "" {
30 entry.post = p
31 c.post[p.ID] = entry
32 }
33 if com.Name() != "" {
34 entry.community = com
35 c.community[com.Name()] = entry
36 }
37 }
39 func (c *cache) delete(p Post, com Community) {
40 c.mu.Lock()
41 defer c.mu.Unlock()
42 delete(c.post, p.ID)
43 delete(c.community, com.Name())
44 }
46 // max-age=50
47 func parseMaxAge(s string) (time.Duration, error) {
48 var want string
49 elems := strings.Split(s, ",")
50 for i := range elems {
51 elems[i] = strings.TrimSpace(elems[i])
52 if strings.HasPrefix(elems[i], "max-age") {
53 want = elems[i]
54 }
55 }
56 _, num, found := strings.Cut(want, "=")
57 if !found {
58 return 0, fmt.Errorf("missing = separator")
59 }
60 n, err := strconv.Atoi(num)
61 if err != nil {
62 return 0, fmt.Errorf("parse seconds: %w", err)
63 }
64 return time.Duration(n) * time.Second, nil
65 }
67 // Cache-Control: public, max-age=50
68 func extractMaxAge(header http.Header) string {
69 cc := header.Get("Cache-Control")
70 if !strings.Contains(cc, "max-age=") {
71 return ""
72 }
73 return cc
74 }