Home > Net >  How to use gcp signed url with custom headers in Go
How to use gcp signed url with custom headers in Go

Time:02-16

I am trying to set the x-goog-meta-reference in the header section dynamically so i want to pass an argument called reference in the function signature and assign that to the x-goog-meta-reference in the header. See x-goog-meta-reference in my code sample below. I followed this link regarding canonical requests.

My sample code is from here but it is the edited version of my prod code.

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
}

I tried looking at some examples but all of them are s3 and I did not run into any gcp sample code. However, I did find this issue but i was not able to figure it out myself.

CodePudding user response:

As @dazwilkin mentions, fmt.Sprintf is good enough for this case, but you can also use this library that I ported from mozilla

import (
    "context"
    "fmt"
    "time"

    "cloud.google.com/go/storage"
    "github.com/dkbyo/go-stringhttpheader"
)

type Headers struct {
    GoogleMetaReference string `header:"x-goog-meta-reference"`
}

func GenerateSignedURL(bucket string, key string, expiration time.Time,
) (string, error) {
    ctx := context.Background()
    gcsClient, err := storage.NewClient(ctx)
    if err != nil {
        return "", fmt.Errorf("storage.NewClient: %v", err)
    }
    defer gcsClient.Close()
    headers := Headers{
        GoogleMetaReference: "xxx",
    }
    fmt.Print(stringhttpheader.Encode(headers))
    stringheaders, _ := stringhttpheader.Encode(headers)
    //storage.SignedURL()
    opts := &storage.SignedURLOptions{
        Scheme:      storage.SigningSchemeV4,
        Method:      "PUT",
        ContentType: "text/csv",
        Headers:     stringheaders,
        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
}
  • Related