package main import ( "context" "fmt" "net" "time" "github.com/pion/mdns" "golang.org/x/net/ipv4" ) type Proxy struct { SCHEME string HOSTNAME string PORT int } func (p *Proxy) Format() string { if p.PORT == 0 { return fmt.Sprintf(TMPL_WITHOUT_PORT, p.SCHEME, p.HOSTNAME) } else { return fmt.Sprintf(TMPL, p.SCHEME, p.HOSTNAME, p.PORT) } } var DEFAULT_PORT = 8000 var DEFAULT_PROXY = Proxy{SCHEME: "https", HOSTNAME: "apt.paulbsd.com", PORT: 0} const TMPL = "%s://%s:%d" const TMPL_WITHOUT_PORT = "%s://%s" func main() { addr, err := net.ResolveUDPAddr("udp", mdns.DefaultAddress) if err != nil { panic(err) } l, err := net.ListenUDP("udp4", addr) if err != nil { panic(err) } server, err := mdns.Server(ipv4.NewPacketConn(l), &mdns.Config{}) if err != nil { panic(err) } ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() _, src, err := server.Query(ctx, "apt.local") if err != nil { var res = DEFAULT_PROXY fmt.Println(res.Format()) return } var res = Proxy{SCHEME: "http", HOSTNAME: src.String(), PORT: DEFAULT_PORT} fmt.Println(res.Format()) }