Created
December 5, 2018 16:02
-
-
Save bobveznat/9bf7e2f789ea68edca7cb922f56aef92 to your computer and use it in GitHub Desktop.
Using the AWS S3 golang SDK with Google default credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/request" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/s3" | |
"golang.org/x/oauth2/google" | |
"log" | |
) | |
// This isn't production worthy code. It's just showing which libraries and entrypoints you might use to do this. | |
func main() { | |
s3client := s3.New(session.New(), aws.NewConfig().WithEndpoint("storage.googleapis.com").WithRegion("us-central1")) | |
s3client.Handlers.Sign.Clear() | |
s3client.Handlers.Sign.PushBackNamed(request.NamedHandler{ | |
Name: "GoogleOauth", | |
Fn: func(req *request.Request) { | |
creds, err := google.FindDefaultCredentials(context.Background(), "https://storage.googleapis.com") | |
if err != nil { | |
log.Printf("No creds: %s", err) | |
} else { | |
token, err := creds.TokenSource.Token() | |
if err != nil { | |
log.Printf("No token source: %s", err) | |
} else { | |
authzHeaderVal := fmt.Sprintf("%s %s", token.TokenType, token.AccessToken) | |
log.Printf("Signing that beast! %s", authzHeaderVal) | |
req.HTTPRequest.Header.Set("Authorization", authzHeaderVal) | |
} | |
} | |
}, | |
}) | |
headOp := &s3.HeadObjectInput{ | |
Bucket: aws.String("mybucket"), | |
Key: aws.String("whatever/path"), | |
} | |
_, err := s3client.HeadObject(headOp) | |
if err != nil { | |
log.Printf("Head failed: %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment