Skip to content

Instantly share code, notes, and snippets.

@poindextrose
Last active January 22, 2024 22:59
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save poindextrose/afa4d4bb5e93c4c3de77 to your computer and use it in GitHub Desktop.
Save poindextrose/afa4d4bb5e93c4c3de77 to your computer and use it in GitHub Desktop.
Example on how to create a signed URL on Google Cloud Storage with Go
package main
import (
"fmt"
"time"
"google.golang.org/cloud/storage"
)
const (
projectID = "myProject-1234"
)
func main() {
bucket := "mybucket"
filename := "myFilename"
method := "PUT"
expires := time.Now().Add(time.Second * 60)
url, err := storage.SignedURL(bucket, filename, &storage.SignedURLOptions{
GoogleAccessID: "XXXXXX@developer.gserviceaccount.com",
PrivateKey: []byte("-----BEGIN PRIVATE KEY-----\nXXXXXXXX"),
Method: method,
Expires: expires,
})
if err != nil {
fmt.Println("Error " + err.Error())
}
fmt.Println("URL = " + url)
}
@bithavoc
Copy link

thank you

@tamalsaha
Copy link

tamalsaha commented Jul 25, 2019

Thanks for the snippet. I made some adjustments to make it work with the json key file you can download from Google cloud console.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"time"

	"cloud.google.com/go/storage"
	"golang.org/x/oauth2/google"
)

func main() {
	sakeyFile := "/home/tamal/Downloads/xyz.json"

	saKey, err := ioutil.ReadFile(sakeyFile)
	if err != nil {
		log.Fatalln(err)
	}

	cfg, err := google.JWTConfigFromJSON(saKey)
	if err != nil {
		log.Fatalln(err)
	}

	bucket := "go-cloud"
	filename := "mypic3.json"
	method := "GET"
	expires := time.Now().Add(time.Second * 60)

	url, err := storage.SignedURL(bucket, filename, &storage.SignedURLOptions{
		GoogleAccessID: cfg.Email,
		PrivateKey:     cfg.PrivateKey,
		Method:         method,
		Expires:        expires,
	})
	if err != nil {
		fmt.Println("Error " + err.Error())
	}
	fmt.Println(url)
}

@johnrhampton
Copy link

Great example, thanks!

@ORESoftware
Copy link

how do we get an Unsigned URL? so dumb I can't find that

@tusharjagtap-bc
Copy link

once you get the signed URL, how can I use curl command to upload a file? Can someone please help with an example?

@JorgeRSG
Copy link

JorgeRSG commented Aug 1, 2022

Indeed, it would look something like this:
curl -X PUT --progress-bar -H 'Content-Type: application/mxf' --upload-file 'path_to_file.txt' 'Signed URL' where Content-Type: application/mxf will vary based on the type of file you're uploading, and path_to_file.txt and Signed URL need to be replaced with your actual values.

@tusharjagtap-bc
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment