http-boot-config/config/discover/discover.go
2024-04-30 18:42:35 +02:00

59 lines
1.5 KiB
Go

package discover
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"time"
"git.faercol.me/faercol/http-boot-config/config/config"
)
var ErrNoServer = errors.New("no server found")
var discoveryMsg = []byte("BOOT_DISCOVER")
type discoveryPayload struct {
ManagementAddress string `json:"managementAddress"`
Version string `json:"version"`
}
func DiscoverServer(conf config.Autodiscovery) (string, error) {
raddr, err := net.ResolveUDPAddr("udp", conf.DiscoveryAddr)
if err != nil {
return "", fmt.Errorf("invalid discovery address: %w", err)
}
conn, err := net.ListenUDP("udp", nil)
if err != nil {
return "", fmt.Errorf("failed to dial UDP multicast group: %w", err)
}
defer conn.Close()
n, err := conn.WriteToUDP(discoveryMsg, raddr)
if err != nil {
return "", fmt.Errorf("failed to write to UDP connection: %w", err)
}
if n < len(discoveryMsg) {
return "", fmt.Errorf("failed to write the entire message (%d/%d)", n, len(discoveryMsg))
}
conn.SetReadDeadline(time.Now().Add(conf.Timeout))
resp := make([]byte, 2048)
if _, err := conn.Read(resp); err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
return "", ErrNoServer
}
return "", fmt.Errorf("failed to read response from server: %w", err)
}
var payload discoveryPayload
if err := json.Unmarshal(bytes.Trim(resp, "\x00"), &payload); err != nil {
return "", fmt.Errorf("failed to parse response from server: %w", err)
}
return payload.ManagementAddress, nil
}