-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
79 lines (68 loc) · 1.51 KB
/
engine.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
package simple
import (
"context"
"fmt"
"github.com/youngfs/youngfs/pkg/errors"
"github.com/youngfs/youngfs/pkg/idmint"
"github.com/youngfs/youngfs/pkg/idmint/uuid"
"io"
"os"
"path/filepath"
)
type Engine struct {
dir string
idGen idmint.Mint
}
func New(dir string, options ...Option) (*Engine, error) {
cfg := &config{
idGen: uuid.NewSimpleUUID(),
}
for _, opt := range options {
opt.apply(cfg)
}
stat, err := os.Stat(dir)
if err != nil {
return nil, err
}
if !stat.IsDir() {
return nil, fmt.Errorf("%s is not a directory", dir)
}
return &Engine{dir, cfg.idGen}, nil
}
func (e *Engine) PutChunk(ctx context.Context, reader io.Reader, endpoints ...string) (string, error) {
id, err := e.idGen.String(ctx)
if err != nil {
return "", err
}
filePath := filepath.Join(e.dir, id)
file, err := os.Create(filePath)
if err != nil {
return "", err
}
defer func() {
_ = file.Close()
}()
_, err = io.Copy(file, reader)
if err != nil {
return "", err
}
return id, nil
}
func (e *Engine) GetChunk(ctx context.Context, id string) (io.ReadCloser, error) {
filePath := filepath.Join(e.dir, id)
file, err := os.Open(filePath)
if err != nil {
if os.IsNotExist(err) {
return nil, errors.ErrChunkNotExist
}
return nil, err
}
return file, nil
}
func (e *Engine) DeleteChunk(ctx context.Context, id string) error {
filePath := filepath.Join(e.dir, id)
return os.Remove(filePath)
}
func (e *Engine) GetEndpoints(ctx context.Context) ([]string, error) {
return []string{"localhost"}, nil
}