2fas-server/internal/common/websocket/gorilla_websocket_client.go

66 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-12-31 10:22:38 +01:00
package websocket
import (
"encoding/json"
"fmt"
2022-12-31 10:22:38 +01:00
"net/http"
"net/url"
"path"
2024-03-16 19:05:21 +01:00
"github.com/gorilla/websocket"
2024-03-16 19:05:21 +01:00
app_http "github.com/twofas/2fas-server/internal/common/http"
"github.com/twofas/2fas-server/internal/common/logging"
2022-12-31 10:22:38 +01:00
)
type WebsocketApiClient struct {
wsAddr string
}
func NewWebsocketApiClient(websocketApiUrl string) *WebsocketApiClient {
return &WebsocketApiClient{
wsAddr: websocketApiUrl,
}
}
func (ws *WebsocketApiClient) SendMessage(uri string, message interface{}) error {
u, err := url.Parse(ws.wsAddr)
if err != nil {
return fmt.Errorf("failed to parse %q: %w", ws.wsAddr, err)
}
2022-12-31 10:22:38 +01:00
u.Path = path.Join(u.Path, uri)
msg, err := json.Marshal(message)
if err != nil {
return fmt.Errorf("failed to marshal message: %w", err)
2022-12-31 10:22:38 +01:00
}
logging.WithFields(logging.Fields{
"message": string(msg),
"ws_url": u.String(),
}).Info("Start command `SendWebsocketMessage`")
requestHeaders := http.Header{
app_http.CorrelationIdHeader: []string{app_http.CorrelationId},
}
c, _, err := websocket.DefaultDialer.Dial(u.String(), requestHeaders)
if err != nil {
return fmt.Errorf("failed to dial: %q: %w", u.String(), err)
2022-12-31 10:22:38 +01:00
}
err = c.WriteMessage(websocket.TextMessage, msg)
if err != nil {
logging.WithField("error", err.Error()).Error("Cannot send websocket message")
return fmt.Errorf("failed to write message to the conection: %w", err)
2022-12-31 10:22:38 +01:00
}
err = c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
logging.WithField("error", err.Error()).Error("Cannot close websocket connection")
return fmt.Errorf("failed to write close message to the conection: %w", err)
2022-12-31 10:22:38 +01:00
}
return nil
}