summaryrefslogtreecommitdiff
path: root/source/url.go
blob: 067d48b40a7c7af0c65e026525264a20457d7fd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package source

import (
	"fmt"
	"log/slog"
	"net/netip"
	nurl "net/url"
)

// a simple source that fetches an address from a url.
// sends a http get request to url, and parses whatever it found there.
// can be used to fetch address values from generic "my ip"
// services which don't have direct support.
// note that the address does have to be returned in plain-text!
type urlSource struct {
	log    *slog.Logger
	url    *nurl.URL
	family Family
}

var _ Source = (*urlSource)(nil)

func newURL(log *slog.Logger, cfg Config) (*urlSource, error) {
	log = log.With("source", "url")

	url, err := nurl.ParseRequestURI(cfg.URL)
	if err != nil {
		return nil, fmt.Errorf("invalid url for source: %w", err)
	}

	return &urlSource{log: log, url: url, family: cfg.Family}, nil
}

func (s *urlSource) Supports(f Family) bool { return f == s.family }

func (s *urlSource) Lookup(Family) (netip.Addr, error) {
	s.log.Info(
		"will look up address via fetching from url",
		slog.String("url", s.url.String()),
		slog.String("family", string(s.family)),
	)

	addr, err := fetch(s.url.String(), s.family)
	if err != nil {
		return netip.Addr{}, fmt.Errorf("failed to source address from url: %w", err)
	}

	return addr, nil
}