1
votes

I am working on a project where I need to enable versioning of bucket on Google Cloud Storage using Golang. To be more specific :

  1. How to enable versioning on Already created bucket ?
  2. How to enable versioning on new buckets ?

Note : I have already googled and gone through the documentation of Google Cloud Platform and found the code example of versioning in Java only. Even I have explored the package "cloud.google.com/go/storage" to understand the code but no help.

I am using below library and functions in my code to update buckets :

    import "cloud.google.com/go/storage"

    func configureStorage(bucketID string) (*storage.BucketHandle, error) {
        ctx := context.Background()
        client, err := storage.NewClient(ctx)
        if err != nil {
            log.Printf("An error happened: %v", err)
            return nil, err
        }
        return client.Bucket(bucketID), nil
    }

    func saveFileToStorage(bucketID string, fileName string, contentType string, file multipart.File) {
        StorageBucket, err := configureStorage(bucketID)

        if err != nil {
            log.Fatal(err)
        }

        if StorageBucket == nil {
            log.Printf("Storage Bucket is nil")
            return
        }

        ctx := context.Background()

        wr := StorageBucket.Object(fileName).NewWriter(ctx)
        wr.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}}
        wr.ContentType = contentType

        // Entries are immutable, be aggressive about caching (1 day).
        wr.CacheControl = "public, max-age=86400"

        if _, err := io.Copy(wr, file); err != nil {
            log.Fatal(err)
        }
        if err := wr.Close(); err != nil {
            log.Fatal(err)
        }
    }
2
Its not go related issue , try this cloud.google.com/storage/docs/gsutil/commands/versioningMIkCode
@MIkCode : So, Are you proposing me to do that manually ? I am creating the buckets at the time of User Registration so I need to do that in code itself and looking for a solution in Golang only.Nikhil Maheshwari
Are you going to create a bucket per user ?MIkCode
@MIkCode : Yes, I am planning to do that.Nikhil Maheshwari
dont do that , there is a rate limit for creating buckets . you need to create Main bucket and for each user a folder . BUCKET/User1/file3 ,BUCKET/User2/... ,BUCKET/User3/.. check this best practices cloud.google.com/storage/docs/best-practicesMIkCode

2 Answers

0
votes

You can try this to GET where it tells you whether versioning is enabled.

gsutil versioning get gs://bucket_name

Can try this SET on or off the versioning of the bucket.

gsutil versioning set on gs://bucket_name
0
votes

this seems to work:

client.Bucket("bucket").Update(ctx, storage.BucketAttrsToUpdate{VersioningEnabled: true})