paulbsd-salt/states/apt/templates/apt.go

55 lines
1016 B
Go
Raw Normal View History

2023-07-02 21:32:49 +02:00
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 {
return fmt.Sprintf(TMPL, p.SCHEME, p.HOSTNAME, p.PORT)
}
var DEFAULT_PORT = 8000
var DEFAULT_PROXY = Proxy{SCHEME: "http", HOSTNAME: "apt.paulbsd.com", PORT: 8001}
const TMPL = "%s://%s:%d"
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())
}