func sendCommandPubSub()

in reference-architectures/cloud_deploy_flow/CloudFunctions/cloudDeployApprovals/main.go [127:163]


func sendCommandPubSub(ctx context.Context, m *CommandMessage) error {
	// Initializes Pub/Sub client using the project ID from config
	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) // Returns error if client creation fails
	}
	defer client.Close() // Ensures client is closed after message is sent

	// Defines the target topic using config data
	t := client.Topic(c.SendTopicID)

	// Encodes the CommandMessage as JSON
	jsonData, err := json.Marshal(m)
	if err != nil {
		return fmt.Errorf("json.Marshal: %v", err) // Returns error if JSON encoding fails
	}
	log.Printf("Sending message to PubSub") // Logs before publishing

	// Publishes the message to the topic
	result := t.Publish(ctx, &pubsub.Message{
		Data: jsonData, // Publishes JSON data as message
	})

	// Waits for the publish result, logging ID or error if present
	id, err := result.Get(ctx)
	log.Printf("ID: %s, err: %v", id, err)
	if err != nil {
		fmt.Printf("Get: %v", err) // Logs any error on publish
		return nil
	}

	log.Printf("Published a message; msg ID: %v\n", id) // Logs message ID if successful
	return nil
}