github.com/epsagon/epsagon-go@v1.39.0/example/s3_example/write_v2/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "log" 8 "os" 9 "strings" 10 "time" 11 12 "github.com/aws/aws-lambda-go/events" 13 "github.com/aws/aws-lambda-go/lambda" 14 "github.com/aws/aws-sdk-go-v2/aws" 15 "github.com/aws/aws-sdk-go-v2/aws/external" 16 "github.com/aws/aws-sdk-go-v2/service/s3" 17 "github.com/epsagon/epsagon-go/epsagon" 18 "github.com/google/uuid" 19 ) 20 21 func s3WriteHandler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { 22 log.Println("In s3WriteHandler, received body: ", request.Body) 23 24 cfg, err := external.LoadDefaultAWSConfig() 25 if err != nil { 26 panic("Failed to load default aws config") 27 } 28 cfg.Region = "eu-west-1" 29 svc := epsagon.WrapAwsV2Service(s3.New(cfg)).(*s3.Client) 30 31 // Create a context with a timeout that will abort the upload if it takes 32 // more than the passed in timeout. 33 ctx := context.Background() 34 var cancelFn func() 35 timeout := time.Minute * 2 36 if timeout > 0 { 37 ctx, cancelFn = context.WithTimeout(ctx, timeout) 38 } 39 // Ensure the context is canceled to prevent leaking. 40 // See context package for more information, https://golang.org/pkg/context/ 41 defer cancelFn() 42 43 data := "Hello World" 44 myBucket := os.Getenv("BUCKET_NAME") 45 key := uuid.New().String() 46 47 if len(myBucket) == 0 { 48 errMsg := "ERROR: You need to assign BUCKET_NAME env" 49 log.Println(errMsg) 50 return events.APIGatewayProxyResponse{Body: errMsg, StatusCode: 500}, nil 51 } 52 53 req := svc.PutObjectRequest(&s3.PutObjectInput{ 54 Bucket: &myBucket, 55 Key: &key, 56 Body: strings.NewReader(data), 57 }) 58 59 if _, err := req.Send(ctx); err != nil { 60 var cerr *aws.RequestCanceledError 61 var errMsg string 62 if errors.As(err, &cerr) { 63 errMsg = fmt.Sprintf("upload caceled due to timeout, %v", err) 64 } else { 65 errMsg = fmt.Sprintf("Failed to upload object: %v", err) 66 } 67 log.Println(errMsg) 68 return events.APIGatewayProxyResponse{Body: errMsg, StatusCode: 500}, err 69 } 70 71 log.Printf("Succesfully uploaded file.") 72 return events.APIGatewayProxyResponse{Body: request.Body, StatusCode: 200}, nil 73 } 74 75 func main() { 76 log.Println("enter main") 77 config := epsagon.NewTracerConfig("s3-test-go", "") 78 config.Debug = true 79 lambda.Start(epsagon.WrapLambdaHandler(config, s3WriteHandler)) 80 log.Println("exit main") 81 }