|
- package cdsapi
-
- import (
- "context"
- "fmt"
- "io"
- "net/http"
- "path/filepath"
- "strings"
- "time"
-
- v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
- "github.com/aws/aws-sdk-go-v2/credentials"
- "gitlink.org.cn/cloudream/common/sdks"
- "gitlink.org.cn/cloudream/common/utils/http2"
- "gitlink.org.cn/cloudream/common/utils/math2"
- "gitlink.org.cn/cloudream/common/utils/serder"
- )
-
- func MakeIPFSFilePath(fileHash string) string {
- return filepath.Join("ipfs", fileHash)
- }
-
- func ParseJSONResponse[TBody any](resp *http.Response) (TBody, error) {
- var ret TBody
- contType := resp.Header.Get("Content-Type")
- if strings.Contains(contType, http2.ContentTypeJSON) {
- var err error
- if ret, err = serder.JSONToObjectStreamEx[TBody](resp.Body); err != nil {
- return ret, fmt.Errorf("parsing response: %w", err)
- }
-
- return ret, nil
- }
-
- cont, err := io.ReadAll(resp.Body)
- if err != nil {
- return ret, fmt.Errorf("unknow response content type: %s, status: %d", contType, resp.StatusCode)
- }
- strCont := string(cont)
-
- return ret, fmt.Errorf("unknow response content type: %s, status: %d, body(prefix): %s", contType, resp.StatusCode, strCont[:math2.Min(len(strCont), 200)])
- }
-
- func JSONAPI[Resp sdks.APIResponse, Req sdks.APIRequest](cfg *Config, cli *http.Client, req Req) (Resp, error) {
- var re Resp
-
- param := req.MakeParam()
-
- httpReq, err := param.MakeRequest(cfg.URL)
- if err != nil {
- return re, err
- }
-
- if cfg.AccessKey != "" && cfg.SecretKey != "" {
- prod := credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, "")
- cred, err := prod.Retrieve(context.TODO())
- if err != nil {
- return re, err
- }
-
- signer := v4.NewSigner()
- err = signer.SignHTTP(context.Background(), cred, httpReq, "", AuthService, AuthRegion, time.Now())
- if err != nil {
- return re, err
- }
- }
-
- resp, err := cli.Do(httpReq)
- if err != nil {
- return re, err
- }
-
- err = re.ParseResponse(resp)
- return re, err
- }
-
- func JSONAPINoData[Resp sdks.APIResponse, Req sdks.APIRequest](cfg *Config, cli *http.Client, req Req) error {
- param := req.MakeParam()
-
- httpReq, err := param.MakeRequest(cfg.URL)
- if err != nil {
- return err
- }
-
- if cfg.AccessKey != "" && cfg.SecretKey != "" {
- prod := credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, "")
- cred, err := prod.Retrieve(context.TODO())
- if err != nil {
- return err
- }
-
- signer := v4.NewSigner()
- err = signer.SignHTTP(context.Background(), cred, httpReq, "", AuthService, AuthRegion, time.Now())
- if err != nil {
- return err
- }
- }
-
- resp, err := cli.Do(httpReq)
- if err != nil {
- return err
- }
-
- return sdks.ParseCodeDataJSONResponse(resp, any(nil))
- }
|