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

60 lines
1.1 KiB
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 {
2023-07-15 19:53:46 +02:00
if p.PORT == 0 {
return fmt.Sprintf(TMPL_WITHOUT_PORT, p.SCHEME, p.HOSTNAME)
} else {
2023-07-02 21:32:49 +02:00
return fmt.Sprintf(TMPL, p.SCHEME, p.HOSTNAME, p.PORT)
}
2023-07-15 19:53:46 +02:00
}
2023-07-02 21:32:49 +02:00
var DEFAULT_PORT = 8000
2023-07-15 19:53:46 +02:00
var DEFAULT_PROXY = Proxy{SCHEME: "https", HOSTNAME: "apt.paulbsd.com", PORT: 0}
2023-07-02 21:32:49 +02:00
const TMPL = "%s://%s:%d"
2023-07-15 19:53:46 +02:00
const TMPL_WITHOUT_PORT = "%s://%s"
2023-07-02 21:32:49 +02:00
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())
}