61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package worker
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.lastassault.de/speatzle/morffix/config"
|
|
"git.lastassault.de/speatzle/morffix/constants"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"nhooyr.io/websocket"
|
|
)
|
|
|
|
uuid := uuid.New()
|
|
slog.InfoContext(ctx, "Connecting to Server...", "Address", conf.Worker.Address)
|
|
headers.Add(constants.SHARED_SECRET_HEADER, conf.SharedSecret)
|
|
headers.Add(constants.UUID_HEADER, uuid.String())
|
|
c, res, err := websocket.Dial(ctx, conf.Worker.Address, &websocket.DialOptions{
|
|
HTTPHeader: headers,
|
|
})
|
|
if err != nil {
|
|
if res != nil {
|
|
b, _ := io.ReadAll(res.Body)
|
|
slog.ErrorContext(ctx, "Error Connecting to Server", "err", err, "code", res.Status, "body", b)
|
|
|
|
} else {
|
|
slog.ErrorContext(ctx, "Error Connecting to Server", "err", err)
|
|
}
|
|
return
|
|
}
|
|
go func() {
|
|
time.Sleep(time.Second * 5)
|
|
c.Write(ctx, websocket.MessageText, []byte("test"))
|
|
}()
|
|
|
|
slog.InfoContext(ctx, "Waiting for Messages")
|
|
for {
|
|
err = readMessage(ctx, c)
|
|
if websocket.CloseStatus(err) == websocket.StatusNormalClosure || websocket.CloseStatus(err) == websocket.StatusAbnormalClosure || websocket.CloseStatus(err) == websocket.StatusGoingAway {
|
|
slog.InfoContext(ctx, "Websocket Closed")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.ErrorContext(ctx, "Error Reading Websocket Message", "err", err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func readMessage(ctx context.Context, c *websocket.Conn) error {
|
|
t, data, err := c.Read(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
slog.InfoContext(ctx, "Got Websocket Message", "type", t.String(), "data", data)
|
|
return nil
|
|
}
|