清理任务时不再调用 Storage.DeleteByTask 方法,因为当前 OSS 服务暂未提供删除接口。 从 StorageService 接口和 ossStorage 实现中移除 DeleteByTask 方法,并更新清理逻辑。
84 lines
2.4 KiB
Go
84 lines
2.4 KiB
Go
package service
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"fmt"
|
||
"mime/multipart"
|
||
|
||
"model-asynch/model/entity"
|
||
|
||
commonHttp "gitea.com/red-future/common/http"
|
||
"github.com/gogf/gf/v2/frame/g"
|
||
"github.com/gogf/gf/v2/util/gconv"
|
||
)
|
||
|
||
// 对接你们的 oss 文件服务:POST oss/file/uploadFile (multipart/form-data)
|
||
type ossStorage struct{}
|
||
|
||
type uploadFileResponse struct {
|
||
FileURL string `json:"fileURL"` // 文件 URL
|
||
FileSize int `json:"fileSize"` // 文件大小(字节)
|
||
FileName string `json:"fileName"` // 文件名
|
||
FileFormat string `json:"fileFormat"` // 文件格式
|
||
FileAddressPrefix string `json:"fileAddressPrefix"` // 文件地址前缀
|
||
}
|
||
|
||
func (s *ossStorage) UploadByTask(ctx context.Context, _ *entity.AsynchTask, data []byte, fileExt string, _ string) (ossURL string, err error) {
|
||
// ossUrl := g.Cfg().MustGet(ctx, "oss.addr", "192.168.3.30:9000").String()
|
||
|
||
// multipart
|
||
body := &bytes.Buffer{}
|
||
writer := multipart.NewWriter(body)
|
||
|
||
ext := fileExt
|
||
if ext == "" {
|
||
ext = ".bin"
|
||
}
|
||
if ext[0] != '.' {
|
||
ext = "." + ext
|
||
}
|
||
|
||
part, err := writer.CreateFormFile("file", "")
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
if _, err := part.Write(data); err != nil {
|
||
return "", err
|
||
}
|
||
contentType := writer.FormDataContentType()
|
||
if err := writer.Close(); err != nil {
|
||
return "", err
|
||
}
|
||
|
||
headers := forwardHeaders(ctx)
|
||
headers["Content-Type"] = contentType
|
||
|
||
fullURL := "oss/file/uploadFile"
|
||
g.Log().Infof(ctx, "[OSS] upload start url=%s size=%d", fullURL, len(data))
|
||
|
||
var resp uploadFileResponse
|
||
if err := commonHttp.Post(ctx, fullURL, headers, &resp, body.Bytes()); err != nil {
|
||
return "", err
|
||
}
|
||
if resp.FileURL == "" {
|
||
return "", fmt.Errorf("OSS服务返回错误: 上传失败")
|
||
}
|
||
g.Log().Infof(ctx, "[OSS] upload success url=%s filename=%s size=%d format=%s", resp.FileURL, resp.FileName, resp.FileSize, resp.FileFormat)
|
||
return resp.FileURL, nil
|
||
}
|
||
|
||
// setTaskHeadersToCtx 把任务入库时保存的 header 信息注入 ctx,给 worker 调 OSS 用
|
||
func setTaskHeadersToCtx(ctx context.Context, headers map[string]string) context.Context {
|
||
if headers == nil {
|
||
return ctx
|
||
}
|
||
if v := gconv.String(headers["Authorization"]); v != "" {
|
||
ctx = context.WithValue(ctx, "token", v)
|
||
}
|
||
if v := gconv.String(headers["X-User-Info"]); v != "" {
|
||
ctx = context.WithValue(ctx, "xUserInfo", v)
|
||
}
|
||
return ctx
|
||
}
|