Created
February 24, 2023 17:49
-
-
Save wthorp/8463dad5d5181ce17e8454bece43c328 to your computer and use it in GitHub Desktop.
WIP AWS Lambda Presigned URLs
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 ( | |
"fmt" | |
"time" | |
"github.com/aws/aws-lambda-go/lambda" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/credentials" | |
"github.com/aws/aws-sdk-go/aws/request" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/s3" | |
) | |
const ( | |
storjS3Bucket = "files" | |
storjS3Id = "<access key>" | |
storjS3Secret = "<secret key>" | |
storjS3URL = "https://gateway.storjshare.io/" | |
) | |
type Request struct { | |
Key string `json:"key"` | |
Method string `json:"method"` | |
} | |
type Response struct { | |
Url string `json:"url"` | |
} | |
func main() { | |
lambda.Start(handleRequest) | |
} | |
// HandleRequest accepts an S3 key and presigned URL method type, and returns | |
// a presigned URL. It is designed to be used directly as a Lambda function URL. | |
// https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html | |
func handleRequest(r Request) (*Response, error) { | |
if len(r.Key) == 0 { | |
return nil, fmt.Errorf("request is missing 'key' parameter") | |
} | |
if len(r.Method) == 0 { | |
return nil, fmt.Errorf("request is missing 'method' parameter") | |
} | |
sess, err := session.NewSession(&aws.Config{ | |
Credentials: credentials.NewStaticCredentials(storjS3Id, storjS3Secret, ""), | |
Endpoint: aws.String(storjS3URL), | |
Region: aws.String("us-east-1"), | |
}) | |
if err != nil { | |
return nil, fmt.Errorf("failed to create AWS S3 session") | |
} | |
svc := s3.New(sess) | |
var req *request.Request | |
switch r.Method { | |
case "GET": | |
req, _ = svc.GetObjectRequest(&s3.GetObjectInput{Bucket: aws.String(storjS3Bucket), Key: &r.Key}) | |
case "POST": | |
req, _ = svc.PutObjectRequest(&s3.PutObjectInput{Bucket: aws.String(storjS3Bucket), Key: &r.Key}) | |
default: | |
return nil, fmt.Errorf("the request verb is invalid") | |
} | |
urlStr, err := req.Presign(15 * time.Minute) | |
if err != nil { | |
return nil, fmt.Errorf("failed to presign request") | |
} | |
return &Response{Url: urlStr}, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment