Add Basic Websocket Server/Worker Connection
This commit is contained in:
parent
01e34936e9
commit
9ac9ed8fe2
9 changed files with 218 additions and 7 deletions
61
worker/worker.go
Normal file
61
worker/worker.go
Normal file
|
@ -0,0 +1,61 @@
|
|||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.lastassault.de/speatzle/morffix/config"
|
||||
"git.lastassault.de/speatzle/morffix/constants"
|
||||
|
||||
"nhooyr.io/websocket"
|
||||
)
|
||||
|
||||
func Start(conf config.Config) {
|
||||
ctx := context.Background()
|
||||
headers := http.Header{}
|
||||
|
||||
slog.InfoContext(ctx, "Connecting to Server...", "Address", conf.Worker.Address)
|
||||
headers.Add(constants.SHARED_SECRET_HEADER, conf.SharedSecret)
|
||||
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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue