fix: protocol v1
This commit is contained in:
@ -3,9 +3,9 @@ package discovery
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/grandcat/zeroconf"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Service is a ReachRS service discovered via MDNS-SD
|
||||
@ -17,19 +17,34 @@ type Service struct {
|
||||
|
||||
// Discover tries to discover ReachRS services on the local network via mDNS-SD
|
||||
func Discover(ctx context.Context) ([]Service, error) {
|
||||
var wg sync.WaitGroup
|
||||
services := make([]Service, 0)
|
||||
|
||||
wg.Add(1)
|
||||
watch, err := Watch(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
for srv := range watch {
|
||||
services = append(services, srv)
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// Watch watches ReachRS services on the local network via mDNS-SD
|
||||
func Watch(ctx context.Context) (chan Service, error) {
|
||||
out := make(chan Service, 0)
|
||||
|
||||
resolver, err := zeroconf.NewResolver()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
services := make([]Service, 0)
|
||||
entries := make(chan *zeroconf.ServiceEntry)
|
||||
|
||||
go func() {
|
||||
defer close(out)
|
||||
|
||||
for e := range entries {
|
||||
var addr *net.IP
|
||||
if len(e.AddrIPv4) > 0 {
|
||||
@ -40,17 +55,14 @@ func Discover(ctx context.Context) ([]Service, error) {
|
||||
AddrV4: addr,
|
||||
Port: e.Port,
|
||||
}
|
||||
services = append(services, srv)
|
||||
out <- srv
|
||||
}
|
||||
wg.Done()
|
||||
|
||||
}()
|
||||
|
||||
if err = resolver.Browse(ctx, "_reach._tcp", ".local", entries); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
return services, nil
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user