2024-08-28 07:28:34 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2024-09-06 18:16:04 +00:00
|
|
|
"math"
|
2024-08-28 07:28:34 +00:00
|
|
|
"net/http"
|
2024-09-06 18:16:04 +00:00
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
2024-08-28 07:28:34 +00:00
|
|
|
)
|
|
|
|
|
2024-08-29 11:51:52 +00:00
|
|
|
const webPort = "80"
|
2024-08-28 07:28:34 +00:00
|
|
|
|
2024-09-06 18:16:04 +00:00
|
|
|
type Config struct {
|
|
|
|
Rabbit *amqp.Connection
|
|
|
|
}
|
2024-08-28 07:28:34 +00:00
|
|
|
|
|
|
|
func main() {
|
2024-09-06 18:16:04 +00:00
|
|
|
// try to connect to rabbitmq
|
|
|
|
rabbitConn, err := connect()
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
defer rabbitConn.Close()
|
|
|
|
log.Println("Connected to RabbitMQ")
|
|
|
|
app := Config{
|
|
|
|
Rabbit: rabbitConn,
|
|
|
|
}
|
2024-08-28 07:28:34 +00:00
|
|
|
|
|
|
|
log.Printf("Starting broker service on port %s\n", webPort)
|
|
|
|
|
|
|
|
// define http server
|
|
|
|
srv := &http.Server{
|
|
|
|
Addr: fmt.Sprintf(":%s", webPort),
|
|
|
|
Handler: app.routes(),
|
|
|
|
}
|
|
|
|
|
2024-09-06 18:16:04 +00:00
|
|
|
err = srv.ListenAndServe()
|
2024-08-28 07:28:34 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
}
|
2024-09-06 18:16:04 +00:00
|
|
|
|
|
|
|
func connect() (*amqp.Connection, error) {
|
|
|
|
var counts int64
|
|
|
|
var connection *amqp.Connection
|
|
|
|
|
|
|
|
// don't continue until rabbit is ready
|
|
|
|
for {
|
|
|
|
c, err := amqp.Dial("amqp://guest:guest@rabbitmq") // XXX: credentials
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("RabbitMQ not yet ready...")
|
|
|
|
counts++
|
|
|
|
} else {
|
|
|
|
connection = c
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if counts > 5 {
|
|
|
|
fmt.Println(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
backOff := time.Duration(math.Pow(float64(counts), 2) * float64(time.Second))
|
|
|
|
log.Println("backing off...")
|
|
|
|
time.Sleep(backOff)
|
|
|
|
}
|
|
|
|
|
|
|
|
return connection, nil
|
|
|
|
}
|