REST_API: RabbitMQ Client

This commit is contained in:
vitaliy 2025-06-11 10:57:08 +03:00
parent 34abd61a19
commit efa0c3aea2

99
code/go/mq/rabbit.go Normal file
View File

@ -0,0 +1,99 @@
package main
import (
"fmt"
"log"
"os"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/streadway/amqp"
)
// Структура для JSON данных
type Code struct {
Id_task string `json:"id_task"`
Tp_runner string `json:"tp_runner"`
Code string `json:"code"`
Test string `json:"test"`
}
func main() {
// Define RabbitMQ server URL.
amqpServerURL := os.Getenv("AMQP_SERVER_URL")
if amqpServerURL == "" {
amqpServerURL = "amqp://guest:guest@localhost:5672/" // Default URL if not set
}
// Create a new RabbitMQ connection.
connectRabbitMQ, err := amqp.Dial(amqpServerURL)
if err != nil {
panic(err)
}
defer connectRabbitMQ.Close()
// Let's start by opening a channel to our RabbitMQ
// instance over the connection we have already
// established.
channelRabbitMQ, err := connectRabbitMQ.Channel()
if err != nil {
panic(err)
}
defer channelRabbitMQ.Close()
// With the instance and declare Queues that we can
// publish and subscribe to.
_, err = channelRabbitMQ.QueueDeclare(
"QueueService1", // queue name
true, // durable
false, // auto delete
false, // exclusive
false, // no wait
nil, // arguments
)
if err != nil {
panic(err)
}
// Create a new Fiber instance.
app := fiber.New()
// Add middleware.
app.Use(
logger.New(), // add simple logger
)
// Add route. ?msg=bla
app.Get("/send", func(c *fiber.Ctx) error {
// Create a message to publish.
// to-do: дописать приемку json
p := new(Code)
// Разбираем JSON из тела запроса и заполняем структуру
_ = c.BodyParser(p);
fmt.Println(p.Code)
message := amqp.Publishing{
ContentType: "text/plain",
Body: []byte(c.Query("msg")),
}
// Attempt to publish a message to the queue.
if err := channelRabbitMQ.Publish(
"", // exchange
"QueueService1", // queue name
false, // mandatory
false, // immediate
message, // message to publish
); err != nil {
return err
}
return nil
})
// Start Fiber API server.
log.Fatal(app.Listen(":3000"))
}