如何在 Go 中使用带有自定义标头的 gcp 签名 url

我正在尝试动态设置标题部分中的 x-goog-meta-reference,因此我想在函数签名中传递一个名为 reference 的参数,并将其分配给标题中的 x-goog-meta-reference。请参阅x-goog-meta-reference下面的代码示例。我关注了这个关于规范请求的链接。

我的示例代码来自这里,但它是我的产品代码的编辑版本。

func GenerateSignedURL(ctx context.Context, bucket string, key string, expiration time.Time,

) (string, error) {

    gcsClient, err := storage.NewClient(ctx)

    if err != nil {

        return "", fmt.Errorf("storage.NewClient: %v", err)

    }

    defer gcsClient.Close()


    storage.SignedURL()

    opts := &storage.SignedURLOptions{

        Scheme:      storage.SigningSchemeV4,

        Method:      "PUT",

        ContentType: "text/csv",

        Headers:     []string{

            "x-goog-meta-reference: xxx", // << I want xxx value to be whatever I pass to this function as an arg

        },

        Expires:     expiration,

    }


    url, err := gcsClient.Bucket(bucket).SignedURL(key, opts)

    if err != nil {

        log.WithContext(ctx).Warn("Failed to generate a GCS signed URL")

        return "", err

    }


    return url, nil

}

我尝试查看一些示例,但它们都是 s3 并且我没有遇到任何 gcp 示例代码。但是,我确实发现了这个问题,但我自己无法弄清楚。



catspeake
浏览 90回答 1
1回答

慕工程0101907

正如@dazwilkin提到的那样,fmt.Sprintf对于这种情况来说已经足够了,但是您也可以使用我从mozilla移植的这个库import (&nbsp; &nbsp; "context"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time"&nbsp; &nbsp; "cloud.google.com/go/storage"&nbsp; &nbsp; "github.com/dkbyo/go-stringhttpheader")type Headers struct {&nbsp; &nbsp; GoogleMetaReference string `header:"x-goog-meta-reference"`}func GenerateSignedURL(bucket string, key string, expiration time.Time,) (string, error) {&nbsp; &nbsp; ctx := context.Background()&nbsp; &nbsp; gcsClient, err := storage.NewClient(ctx)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return "", fmt.Errorf("storage.NewClient: %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; defer gcsClient.Close()&nbsp; &nbsp; headers := Headers{&nbsp; &nbsp; &nbsp; &nbsp; GoogleMetaReference: "xxx",&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Print(stringhttpheader.Encode(headers))&nbsp; &nbsp; stringheaders, _ := stringhttpheader.Encode(headers)&nbsp; &nbsp; //storage.SignedURL()&nbsp; &nbsp; opts := &storage.SignedURLOptions{&nbsp; &nbsp; &nbsp; &nbsp; Scheme:&nbsp; &nbsp; &nbsp; storage.SigningSchemeV4,&nbsp; &nbsp; &nbsp; &nbsp; Method:&nbsp; &nbsp; &nbsp; "PUT",&nbsp; &nbsp; &nbsp; &nbsp; ContentType: "text/csv",&nbsp; &nbsp; &nbsp; &nbsp; Headers:&nbsp; &nbsp; &nbsp;stringheaders,&nbsp; &nbsp; &nbsp; &nbsp; Expires:&nbsp; &nbsp; &nbsp;expiration,&nbsp; &nbsp; }&nbsp; &nbsp; url, err := gcsClient.Bucket(bucket).SignedURL(key, opts)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.WithContext(ctx).Warn("Failed to generate a GCS signed URL")&nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; }&nbsp; &nbsp; return url, nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go