finclip-app-manager/infrastructure/client/httpcall/netdisk.go

98 lines
2.8 KiB
Go
Raw Normal View History

2023-10-31 14:07:26 +08:00
package httpcall
import (
"bytes"
"context"
"encoding/json"
"errors"
"finclip-app-manager/infrastructure/config"
"fmt"
"io"
"mime/multipart"
"net/http"
)
const (
FormDataKey = "file"
ConsumerCustomID = "finstore"
)
type netdiskResponse struct {
Location string `json:"location"`
NetdiskID string `json:"netdiskID"`
ResourceID string `json:"resourceID"`
}
func (c *Client) Download(ctx context.Context, path string) ([]byte, error) {
url := path
rsp, err := c.Request(ctx).Get(url)
if err != nil {
log.Errorf("netdisk download err:%s", err.Error())
return nil, err
}
if rsp.StatusCode() != http.StatusOK {
log.Errorf("netdisk download status code err,code:%d", rsp.StatusCode())
return nil, errors.New("download http code err")
}
return rsp.Body(), nil
}
func (c *Client) DownloadByNetdiskId(ctx context.Context, netdiskId string) ([]byte, error) {
url := fmt.Sprintf("%s%s%s", config.GetConfig().NetdiskHost, config.GetConfig().NetdiskInternalDownloadUrl, netdiskId)
rsp, err := c.Request(ctx).Get(url)
if err != nil {
log.Errorf("netdisk download err:%s", err.Error())
return nil, err
}
if rsp.StatusCode() != http.StatusOK {
log.Errorf("netdisk download status code err,code:%d", rsp.StatusCode())
return nil, errors.New("download http code err")
}
return rsp.Body(), nil
}
func (c *Client) Upload(ctx context.Context, name string, inFile io.Reader, useCdn bool) (string, error) {
url := config.GetConfig().NetdiskHost + config.GetConfig().NetdiskUploadURL
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
headers := map[string]string{
"Accept": "application/json, text/plain, */*",
"Content-Type": writer.FormDataContentType(),
"X-Consumer-Custom-ID": ConsumerCustomID,
"url-call": "internal",
}
rsp, err := c.Request(ctx).
SetFileReader(FormDataKey, name, inFile).
SetContentLength(true).
SetHeaders(headers).
Post(url)
if err != nil {
log.Errorf("netdisk upload request err:", err.Error())
return "", err
}
if rsp.StatusCode() != http.StatusOK {
netdiskRsp := ErrInfo{}
err = json.Unmarshal(rsp.Body(), &netdiskRsp)
if err != nil {
log.Errorf("Failed to unmarshal unmarshal netdiskResponse: %v", err)
return "", err
}
log.Errorf("netdisk upload rsp http status code err,code:", rsp.StatusCode())
return "", errors.New(netdiskRsp.Error)
}
netdiskRsp := netdiskResponse{}
err = json.Unmarshal(rsp.Body(), &netdiskRsp)
if err != nil {
log.Errorf("Failed to unmarshal unmarshal netdiskResponse: %v", err)
return "", err
}
return c.genDownloadUrl(netdiskRsp, useCdn), nil
}
func (c *Client) genDownloadUrl(rsp netdiskResponse, useCdn bool) string {
if useCdn && rsp.Location != "" {
return rsp.Location
}
return config.GetConfig().EntryURL + config.GetConfig().NetdiskDownloadURLPrefix + rsp.NetdiskID
}