apps/posts/storage/local.go 805 B raw
1
package storage
2
3
import (
4
	"context"
5
	"os"
6
	"path/filepath"
7
)
8
9
type Local struct {
10
	Dir string
11
}
12
13
func NewLocal(dir string) *Local { return &Local{Dir: dir} }
14
15
func (l *Local) Put(ctx context.Context, key, contentType string, data []byte) error {
16
	select {
17
	case <-ctx.Done():
18
		return ctx.Err()
19
	default:
20
	}
21
	if err := os.MkdirAll(l.Dir, 0o755); err != nil {
22
		return err
23
	}
24
	return os.WriteFile(filepath.Join(l.Dir, key), data, 0o644)
25
}
26
27
func (l *Local) Delete(ctx context.Context, key string) error {
28
	select {
29
	case <-ctx.Done():
30
		return ctx.Err()
31
	default:
32
	}
33
	err := os.Remove(filepath.Join(l.Dir, key))
34
	if os.IsNotExist(err) {
35
		return nil
36
	}
37
	return err
38
}
39
40
func (l *Local) PublicURL(key string) string { return "/uploads/" + key }
41
func (l *Local) Name() string                { return "local" }