Skip to content

Instantly share code, notes, and snippets.

@lxfontes
Created January 10, 2024 16:09
Show Gist options
  • Save lxfontes/85e6bf115f414795f1fc23ab86ada4d7 to your computer and use it in GitHub Desktop.
Save lxfontes/85e6bf115f414795f1fc23ab86ada4d7 to your computer and use it in GitHub Desktop.
GCP Pubsub Listener
package main
// example
// go run ./main.go <gcp-project-name> <pubsub-subscription-name> | jq -r .payload.source.table
import (
"context"
"fmt"
"os"
"os/signal"
"cloud.google.com/go/pubsub"
)
func main() {
if len(os.Args) < 3 {
fmt.Fprintf(os.Stderr, "usage: %s projectID subscriptionID\n", os.Args[0])
os.Exit(1)
}
projectID := os.Args[1]
subscriptionID := os.Args[2]
fmt.Fprintf(os.Stderr, "projectID: %s, subscriptionID: %s\n", projectID, subscriptionID)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
client, err := pubsub.NewClient(ctx, projectID)
if err != nil {
fmt.Fprintf(os.Stderr, "pubsub.NewClient: %s", err)
os.Exit(1)
}
sub := client.Subscription(subscriptionID)
defer cancel()
sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
fmt.Println(string(msg.Data))
msg.Ack()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment