-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource.go
75 lines (60 loc) · 1.37 KB
/
resource.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
package main
import (
"os"
"io/ioutil"
"errors"
"syscall"
"time"
"strconv"
)
type resource struct {
ID string
Dir string
Content string
}
func (r *resource) commit() error {
err := os.MkdirAll(mainDir+r.Dir, 0777)
if err == os.ErrExist {
return errors.New("path already exists")
}
assert(err)
id := strconv.Itoa(time.Now().Nanosecond())
f, err := os.Create(mainDir + r.Dir + "/" + id)
assert(err)
r.ID = id
_, err = f.Write([]byte(r.Content))
assert(err)
return nil
}
func (r *resource) update() error {
//check err
dir := mainDir + r.Dir + "/" + r.ID
err := os.Truncate(dir, 0)
if err == os.ErrNotExist {
return errors.New("no such directory")
}
assert(err)
f, err := os.OpenFile(dir, os.O_RDWR, 0777)
assert(err)
_, err = f.Write([]byte(r.Content))
assert(err)
return nil
}
func deleteResource(dir, id string) error {
err := os.Remove(mainDir + dir + "/" + id)
if pathError, ok := err.(*os.PathError); ok && pathError.Err == syscall.ENOENT {
return os.ErrNotExist
}
assert(err)
return nil
}
func getResource(dir, id string) (resource, error) {
f, err := os.Open(mainDir + dir + "/" +id)
if pathError, ok := err.(*os.PathError); ok && pathError.Err == syscall.ENOENT {
return resource{}, os.ErrNotExist
}
assert(err)
data, err := ioutil.ReadAll(f)
assert(err)
return resource{Content: string(data), Dir: dir, ID:id}, nil
}