1+ package util
2+
3+ import (
4+ "context"
5+ "encoding/json"
6+ "log"
7+ "os"
8+ "time"
9+ amqp "github.com/rabbitmq/amqp091-go"
10+ )
11+
12+ func EnqueueRunRequest (ctx context.Context , runID string , fileName string , extension string ) error {
13+
14+ // Message represents the structure of our message
15+ type Message struct {
16+ RunId string `json:"runId"`
17+ FileName string `json:"fileName"`
18+ Extension string `json:"extension"`
19+ Timestamp time.Time `json:"timestamp"`
20+ }
21+
22+ // Get RabbitMQ connection string from environment variable or use default
23+ rabbitMQURL := os .Getenv ("RABBITMQ_URL" )
24+ if rabbitMQURL == "" {
25+ rabbitMQURL = "amqp://guest:guest@localhost:5672/"
26+ }
27+
28+ // Connect to RabbitMQ server
29+ conn , err := amqp .Dial (rabbitMQURL )
30+ if err != nil {
31+ log .Fatalf ("Failed to connect to RabbitMQ: %v" , err )
32+ }
33+ defer conn .Close ()
34+
35+ // Create a channel
36+ ch , err := conn .Channel ()
37+ if err != nil {
38+ log .Fatalf ("Failed to open a channel: %v" , err )
39+ }
40+ defer ch .Close ()
41+
42+ // Declare a queue
43+ queueName := "task_queue"
44+ q , err := ch .QueueDeclare (
45+ queueName , // name
46+ true , // durable
47+ false , // delete when unused
48+ false , // exclusive
49+ false , // no-wait
50+ nil , // arguments
51+ )
52+
53+ if err != nil {
54+ log .Fatalf ("Failed to declare a queue: %v" , err )
55+ }
56+
57+
58+ // Create a new message
59+ msg := Message {
60+ RunId : runID ,
61+ FileName : fileName ,
62+ Extension : extension ,
63+ Timestamp : time .Now (),
64+ }
65+
66+ // Convert message to JSON
67+ body , err := json .Marshal (msg )
68+ if err != nil {
69+ log .Printf ("Error marshaling message: %v" , err )
70+ }
71+
72+ // Publish message
73+ err = ch .PublishWithContext (
74+ ctx ,
75+ "" , // exchange
76+ q .Name , // routing key
77+ false , // mandatory
78+ false , // immediate
79+ amqp.Publishing {
80+ DeliveryMode : amqp .Persistent ,
81+ Body : body ,
82+ },
83+ )
84+
85+ if err != nil {
86+ log .Printf ("Failed to publish a message: %v" , err )
87+ }
88+
89+ log .Printf ("Published message: %s" , msg .RunId )
90+
91+
92+ return nil
93+ }
0 commit comments