-
Notifications
You must be signed in to change notification settings - Fork 0
/
documents.go
89 lines (79 loc) · 1.75 KB
/
documents.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
80
81
82
83
84
85
86
87
88
89
package main
import (
"errors"
"github.com/iskendria-pub/iskendria/model"
"io/ioutil"
"os"
"sync"
)
func initDocuments() {
theDocuments = &documents{
path: "./documents",
}
theDocuments.init()
}
type documents struct {
mux sync.Mutex
path string
}
var theDocuments *documents
func (d *documents) init() {
d.mux.Lock()
defer d.mux.Unlock()
_, err := os.Stat(d.path)
switch {
case err == nil:
// Do nothing
case os.IsNotExist(err):
err := os.Mkdir(d.path, 0744)
if err != nil {
panic(err)
}
default:
panic(err)
}
}
func (d *documents) searchDescription(theHash string) ([]byte, bool, error) {
if theHash == "" {
return []byte{}, true, nil
}
d.mux.Lock()
defer d.mux.Unlock()
_, err := os.Stat(d.getPath(theHash))
switch {
case err == nil:
result, readErr := d.readAndCheck(theHash)
return result, true, readErr
case os.IsNotExist(err):
return []byte{}, false, nil
default:
return []byte{}, false, err
}
}
func (d *documents) getPath(theHash string) string {
return d.path + "/" + theHash
}
func (d *documents) readAndCheck(theHash string) ([]byte, error) {
fname := d.getPath(theHash)
resultBytes, err := ioutil.ReadFile(fname)
if err != nil {
return []byte{}, err
}
if model.HashBytes(resultBytes) != theHash {
err := os.Remove(fname)
if err != nil {
panic(err)
}
return []byte{}, errors.New("Removed document because of hash mismatch, hash: " + theHash)
}
return resultBytes, nil
}
func (d *documents) save(theHash string, data []byte) error {
if model.HashBytes(data) != theHash {
return errors.New("Uploaded file does not have hash " + theHash)
}
return ioutil.WriteFile(d.getPath(theHash), data, 0644)
}
func (d *documents) open(theHash string) (*os.File, error) {
return os.Open(d.getPath(theHash))
}