Skip to content

Instantly share code, notes, and snippets.

@cognusion
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cognusion/86d98bf5d109557fc9b2 to your computer and use it in GitHub Desktop.
Save cognusion/86d98bf5d109557fc9b2 to your computer and use it in GitHub Desktop.
Simple Go function to generate a valid S3 Signed URL
package generateSignedS3URL
import (
"fmt"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"net/url"
"time"
)
func generateURL(bucket string, filePath string, awsAccessKeyID string,
awsSecretAccessKey string, httpMethod string, minuteExpire int) string {
if httpMethod == "" {
httpMethod = "GET"
}
// If you need to support multiple regions, you'll need to pass it in,
// and mangle this var correspondingly
endPoint := "s3.amazonaws.com"
// String of the Epoch offset to expire the link in
expire := fmt.Sprintf("%d",int64(time.Now().Unix()) + int64(minuteExpire * 60))
// Raw string to use as the signature
sigString := httpMethod + "\n\n\n" + expire + "\n" + "/" + bucket + "/" + filePath
// We take the base64-encoded HMAC-SHA1 sum of the sigString,
// using the SecretKey as the key
mac := hmac.New(sha1.New, []byte(awsSecretAccessKey))
mac.Write([]byte(sigString))
msum := mac.Sum(nil)
signature := base64.StdEncoding.EncodeToString(msum)
// Compose the query
query := "AWSAccessKeyId=" + url.QueryEscape(awsAccessKeyID) + "&Expires=" + expire + "&Signature=" + url.QueryEscape(signature)
// Return the URL
return "https://" + bucket + "." + endPoint + filePath + "?" + query
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment