chore: 初始化提交
This commit is contained in:
commit
943c0a0e5a
71 files changed
+7122
No files matched your search
@@ -0,0 +1,76 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Local 本地磁盘存储。对外 URL 形如 {publicBaseURL}/files/{key}。
|
||||
type Local struct {
|
||||
root string
|
||||
publicBaseURL string
|
||||
}
|
||||
|
||||
func NewLocal(root, publicBaseURL string) (*Local, error) {
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Local{root: root, publicBaseURL: strings.TrimRight(publicBaseURL, "/")}, nil
|
||||
}
|
||||
|
||||
// Root 供 HTTP 静态路由挂载使用。
|
||||
func (l *Local) Root() string {
|
||||
return l.root
|
||||
}
|
||||
|
||||
func (l *Local) Save(_ context.Context, key string, r io.Reader) (string, error) {
|
||||
target, err := l.resolve(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
file, err := os.Create(target)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if _, err := io.Copy(file, r); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/files/%s", l.publicBaseURL, filepath.ToSlash(key)), nil
|
||||
}
|
||||
|
||||
func (l *Local) Delete(_ context.Context, key string) error {
|
||||
target, err := l.resolve(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Remove(target); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolve 阻断越权路径,确保只能写入存储根目录之内。
|
||||
func (l *Local) resolve(key string) (string, error) {
|
||||
cleaned := filepath.Clean("/" + filepath.ToSlash(key))
|
||||
target := filepath.Join(l.root, cleaned)
|
||||
|
||||
if rel, err := filepath.Rel(l.root, target); err != nil || strings.HasPrefix(rel, "..") {
|
||||
return "", errors.New("非法的存储路径: " + key)
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
var _ Storage = (*Local)(nil)
|
||||
@@ -0,0 +1,14 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Storage 媒体存储抽象。本地磁盘与 S3-compatible 实现同一接口,通过配置切换。
|
||||
// 媒体一律走存储层,画布节点只引用返回的 URL。
|
||||
type Storage interface {
|
||||
// Save 写入文件并返回可对外访问的 URL。
|
||||
Save(ctx context.Context, key string, r io.Reader) (string, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
Reference in new issue
Block a user