87 lines
2.0 KiB
Go
87 lines
2.0 KiB
Go
package lib
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/go-stomp/stomp"
|
|
"golang.org/x/net/websocket"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
type STOMPlib struct {
|
|
client *stomp.Conn
|
|
waitMessages map[string]*time.Timer
|
|
state bool
|
|
brokerURL string
|
|
}
|
|
|
|
func NewSTOMPlib() *STOMPlib {
|
|
s := &STOMPlib{
|
|
client: nil,
|
|
waitMessages: make(map[string]*time.Timer),
|
|
state: os.Getenv("SERVICEBRIDGE_ENABLE") == "true",
|
|
brokerURL: fmt.Sprintf("ws://%s:%s/ws",
|
|
os.Getenv("RABBITMQ_HOST"),
|
|
os.Getenv("RABBITMQ_WS_PORT")),
|
|
}
|
|
|
|
if s.state {
|
|
conn, err := websocket.Dial(s.brokerURL, "", "")
|
|
if err != nil {
|
|
log.Fatalf("Error connecting to WebSocket: %v", err)
|
|
}
|
|
/*
|
|
stomp.ConnOpt.Login(os.Getenv("RABBITMQ_USER_PROD"), os.Getenv("RABBITMQ_PASSWORD_PROD")),
|
|
//stomp.ConnOpt.ReconnectDelay(5*time.Second),
|
|
stomp.ConnOpt.HeartBeat(4*time.Second, 4*time.Second),
|
|
////conn
|
|
*/
|
|
s.client, err = stomp.Connect(conn,
|
|
stomp.ConnOpt.Login(os.Getenv("RABBITMQ_USER_PROD"), os.Getenv("RABBITMQ_PASSWORD_PROD")),
|
|
stomp.ConnOpt.HeartBeat(4*time.Second, 4*time.Second),
|
|
//TODO
|
|
)
|
|
|
|
if err != nil {
|
|
log.Fatalf("Error creating STOMP client: %v", err)
|
|
}
|
|
}
|
|
|
|
return s
|
|
}
|
|
|
|
func (s *STOMPlib) SendMessage(topic, id string, message map[string]interface{}) {
|
|
if s.state && s.client != nil {
|
|
// Преобразование message в JSON
|
|
messageBytes, err := json.Marshal(message)
|
|
if err != nil {
|
|
fmt.Printf("[STOMP ERROR] JSON marshal error: %v\n", err)
|
|
return
|
|
}
|
|
messageStr := string(messageBytes)
|
|
|
|
hash := md5.Sum(messageBytes)
|
|
hashStr := hex.EncodeToString(hash[:])
|
|
if _, exists := s.waitMessages[hashStr]; exists {
|
|
return
|
|
}
|
|
|
|
s.waitMessages[hashStr] = time.AfterFunc(1*time.Second, func() {
|
|
delete(s.waitMessages, hashStr)
|
|
err := s.client.Send(
|
|
fmt.Sprintf("/topic/%s.%s", topic, id),
|
|
"text/plain",
|
|
[]byte(messageStr),
|
|
nil,
|
|
)
|
|
if err != nil {
|
|
fmt.Printf("[STOMP ERROR] %v\n", err)
|
|
}
|
|
})
|
|
}
|
|
}
|