main
Raw Download raw file
 1package content
 2
 3import (
 4	"crypto/sha256"
 5	"encoding/json"
 6	"errors"
 7	"fmt"
 8	"net/url"
 9	"os"
10	"path/filepath"
11)
12
13const (
14	_contentDir       = "content"
15	_metadataFilename = "metadata.json"
16)
17
18var (
19	ErrNotFound  = errors.New("item not found")
20	ErrEmptyFile = errors.New("item empty")
21)
22
23type URLID string // sha256 hex
24
25func NewURLID(u *url.URL) (URLID, error) {
26	hash := sha256.New()
27	_, err := hash.Write([]byte(u.String()))
28	if err != nil {
29		return "", err
30	}
31	hex := fmt.Sprintf("%x", hash.Sum(nil))
32	return URLID(hex), nil
33}
34
35func (id URLID) Dir() string {
36	s := string(id)
37	return filepath.Join(_contentDir, s[0:2], s[2:4], s[4:])
38}
39
40func (id URLID) Path() string {
41	dir := id.Dir()
42	return filepath.Join(dir, _metadataFilename)
43}
44func (id URLID) Temp() string {
45	dir := id.Dir()
46	return filepath.Join(dir, _metadataFilename+".tmp")
47}
48
49func (id URLID) GetItem() (*Item, error) {
50	var item = &Item{}
51	_, err := os.Stat(id.Path())
52	if err != nil {
53		return nil, ErrNotFound
54	}
55
56	b, err := os.ReadFile(id.Path())
57	if err != nil {
58		return nil, err
59	}
60
61	err = json.Unmarshal(b, item)
62	if err != nil {
63		return nil, err
64	}
65	return item, nil
66}