in reference-architectures/cloud_deploy_flow/CloudFunctions/cloudDeployOperations/main.go [116:152]
func sendCommandPubSub(ctx context.Context, m *CommandMessage) error {
// Create a new Pub/Sub client to publish messages.
client, err := pubsub.NewClient(ctx,
c.ProjectId,
option.WithUserAgent("cloud-solutions/platform-engineering-cloud-deploy-pipeline-code-v1"),
)
if err != nil {
return fmt.Errorf("pubsub.NewClient: %v", err)
}
defer client.Close() // Ensure client is closed when done
// Define the topic for message publication based on environment configuration.
t := client.Topic(c.SendTopicID)
// Marshal the CommandMessage into JSON format for the Pub/Sub message data payload.
jsonData, err := json.Marshal(m)
if err != nil {
return fmt.Errorf("json.Marshal: %v", err)
}
log.Printf("Sending message to PubSub")
// Publish the JSON data as a Pub/Sub message and wait for the message ID.
result := t.Publish(ctx, &pubsub.Message{
Data: jsonData, // Serialized JSON command message
})
// Block until the result returns the server-generated ID for the published message.
id, err := result.Get(ctx)
log.Printf("ID: %s, err: %v", id, err)
if err != nil {
fmt.Printf("Get: %v", err)
return nil
}
log.Printf("Published a message; msg ID: %v\n", id)
return nil
}