DEV Community

Rak
Rak

Posted on • Updated on

Creating Bucket (S3) Notifications on AWS with GO

In this tutorial, we’ll explore how to set up bucket notifications in Go, enabling your applications to react to changes in file storage buckets. This is particularly useful in scenarios where you need to monitor a bucket for new file uploads or deletions.

If you haven't used the Nitric SDK before, then start with this tutorial.

1. Create a Bucket Instance

Import the necessary packages and Instantiate a new bucket object. In this tutorial, we'll name our bucket 'assets'.

import (
  "context"
  "fmt"
  "github.com/nitrictech/go-sdk/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  assets := nitric.NewBucket("assets")
  // ...
}
Enter fullscreen mode Exit fullscreen mode

2. Set Up Notifications for File Write Events

To monitor for file write events, specifically for files starting with a certain prefix, use the On method on the bucket object. Let’s trigger notifications for files starting with '/users/images'.

import (
  "context"
  "fmt"

  "github.com/nitrictech/go-sdk/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  assets := nitric.NewBucket("assets")

  // Filter for 'write' events for files starting with '/users/images'
  assets.On(faas.WriteNotification, "/users/images", func(ctx *faas.BucketNotificationContext, _ faas.BucketNotificationHandler) (*faas.BucketNotificationContext, error) {
    fmt.Printf("new profile image for %s was written", ctx.Request.Key())

    return ctx, nil
  })

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}

Enter fullscreen mode Exit fullscreen mode

3. Set Up Notifications for File Delete Events

Similarly, to monitor for file deletion events for any file, set up a notification like so:

  // Filter for 'delete' events for any file
  assets.On(faas.DeleteNotification, "*", func(ctx *faas.BucketNotificationContext, _ faas.BucketNotificationHandler) (*faas.BucketNotificationContext, error) {
    fmt.Printf("%s was deleted", ctx.Request.Key())

    return ctx, nil
  })
Enter fullscreen mode Exit fullscreen mode

Avoid writing or deleting to the bucket from within a notification as this can trigger the notification again, potentially causing an infinite loop which can be costly.

Conclusion

Now you have set up bucket notifications in Go using the Nitric SDK.

This setup will help you monitor file write and delete events, allowing your application to react to changes in your bucket accordingly.

Top comments (0)