]> Sergey Matveev's repositories - btrtrc.git/blob - tracker/client.go
Add ClientConfig.WebTransport
[btrtrc.git] / tracker / client.go
1 package tracker
2
3 import (
4         "context"
5         "net"
6         "net/url"
7
8         "github.com/anacrolix/log"
9
10         trHttp "github.com/anacrolix/torrent/tracker/http"
11         "github.com/anacrolix/torrent/tracker/udp"
12 )
13
14 type Client interface {
15         Announce(context.Context, AnnounceRequest, AnnounceOpt) (AnnounceResponse, error)
16         Close() error
17 }
18
19 type AnnounceOpt = trHttp.AnnounceOpt
20
21 type NewClientOpts struct {
22         Http trHttp.NewClientOpts
23         // Overrides the network in the scheme. Probably a legacy thing.
24         UdpNetwork   string
25         Logger       log.Logger
26         ListenPacket func(network, addr string) (net.PacketConn, error)
27 }
28
29 func NewClient(urlStr string, opts NewClientOpts) (Client, error) {
30         _url, err := url.Parse(urlStr)
31         if err != nil {
32                 return nil, err
33         }
34         switch _url.Scheme {
35         case "http", "https":
36                 return trHttp.NewClient(_url, opts.Http), nil
37         case "udp", "udp4", "udp6":
38                 network := _url.Scheme
39                 if opts.UdpNetwork != "" {
40                         network = opts.UdpNetwork
41                 }
42                 cc, err := udp.NewConnClient(udp.NewConnClientOpts{
43                         Network:      network,
44                         Host:         _url.Host,
45                         Logger:       opts.Logger,
46                         ListenPacket: opts.ListenPacket,
47                 })
48                 if err != nil {
49                         return nil, err
50                 }
51                 return &udpClient{
52                         cl:         cc,
53                         requestUri: _url.RequestURI(),
54                 }, nil
55         default:
56                 return nil, ErrBadScheme
57         }
58 }