nf-disk/internal/handler/connection.go

102 lines
2.2 KiB
Go
Raw Normal View History

2024-09-26 17:54:14 +08:00
package handler
import (
2024-09-27 14:52:10 +08:00
"github.com/loveuer/nf-disk/internal/db"
"github.com/loveuer/nf-disk/internal/manager"
"github.com/loveuer/nf-disk/internal/model"
"github.com/loveuer/nf-disk/internal/s3"
"github.com/loveuer/nf-disk/ndh"
2024-09-26 17:54:14 +08:00
)
func ConnectionTest(c *ndh.Ctx) error {
type Req struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Access string `json:"access"`
Key string `json:"key"`
}
var (
err error
req = new(Req)
)
if err = c.ReqParse(req); err != nil {
return err
}
if req.Endpoint == "" || req.Access == "" || req.Key == "" {
return c.Send400(nil, "endpoint, secret_access, secret_key 是必填项")
}
if _, err = s3.New(c.Context(), req.Endpoint, req.Access, req.Key); err != nil {
return c.Send500(err.Error(), "连接失败")
}
2024-09-27 14:52:10 +08:00
return c.Send200("连接测试成功")
}
func ConnectionCreate(c *ndh.Ctx) error {
type Req struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Access string `json:"access"`
Key string `json:"key"`
Force bool `json:"force"`
}
var (
err error
req = new(Req)
client *s3.Client
)
if err = c.ReqParse(req); err != nil {
return err
}
if req.Endpoint == "" || req.Access == "" || req.Key == "" {
return c.Send400(nil, "endpoint, secret_access, secret_key 是必填项")
}
if client, err = s3.New(c.Context(), req.Endpoint, req.Access, req.Key); err != nil {
return c.Send500(err.Error(), "连接失败")
}
if req.Name == "" {
req.Name = req.Endpoint
}
connection := &model.Connection{
Name: req.Name,
Endpoint: req.Endpoint,
Access: req.Access,
Key: req.Key,
}
if err = connection.Create(db.Default.Session()); err != nil {
return c.Send500(err.Error(), "创建连接失败(1)")
}
if err = manager.Register(connection, client); err != nil {
return c.Send500(err.Error(), "创建连接失败(2)")
}
return c.Send200(connection, "创建连接成功")
}
func ConnectionList(c *ndh.Ctx) error {
var (
err error
list = make([]*model.Connection, 0)
)
if err = db.Default.Session().Model(&model.Connection{}).
Find(&list).
Error; err != nil {
return err
}
return c.Send200(map[string]any{"list": list})
2024-09-26 17:54:14 +08:00
}