~adnano/astronaut

ref: 72ba913688a9d2dafb0bfdf11a5cee16685ce98a astronaut/cache.go -rw-r--r-- 1.7 KiB
72ba9136Adnan Maolood Use scfg to configure settings 4 months ago
                                                                                
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
80
81
82
83
84
85
86
87
package main

import (
	"bufio"
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"git.sr.ht/~adnano/go-gemini"
)

var cacheDir string

func shouldCache(req *gemini.Request) bool {
	// Don't cache:
	// - Requests with queries
	// - Requests with certificates
	return len(req.URL.RawQuery) == 0 && !req.URL.ForceQuery && req.Certificate == nil
}

func cacheId(req *gemini.Request) string {
	var buf bytes.Buffer
	buf.Write([]byte(req.URL.Host))
	buf.Write([]byte(req.URL.Path))
	sum := sha256.Sum256(buf.Bytes())
	return hex.EncodeToString(sum[:])
}

func cacheGet(req *gemini.Request) *gemini.Response {
	const ttl = time.Hour

	if !shouldCache(req) {
		return nil
	}

	id := cacheId(req)
	f, err := os.Open(filepath.Join(cacheDir, id))
	if err != nil {
		if !os.IsNotExist(err) {
			log.Printf("Error reading cache: %v", err)
		}
		return nil
	}
	stat, err := f.Stat()
	if err != nil {
		log.Printf("Error reading cache: %v", err)
		return nil
	}
	if time.Now().Sub(stat.ModTime()) >= ttl {
		return nil
	}
	resp, err := gemini.ReadResponse(f)
	if err != nil {
		log.Printf("Error reading cache: %v", err)
		return nil
	}
	return resp
}

func cachePut(req *gemini.Request, resp *gemini.Response) {
	if !shouldCache(req) {
		return
	}
	if resp.Status != gemini.StatusSuccess {
		return
	}

	id := cacheId(req)
	f, err := os.OpenFile(filepath.Join(cacheDir, id), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if err != nil {
		if !os.IsNotExist(err) {
			log.Printf("Error writing cache: %v", err)
		}
		return
	}
	w := bufio.NewWriter(f)
	w.WriteString(strconv.Itoa(int(resp.Status)))
	w.WriteByte(' ')
	w.WriteString(resp.Meta)
	w.WriteString("\r\n")
	resp.Body = &teeReader{resp.Body, w}
}