2
0
mirror of synced 2025-02-23 14:18:13 +00:00

Modify HTTP request before sending (#787)

* set up custom request headers

* apply headers defined in torrent client config

* add error handling

* provide better name for method

* update error message

* only apply HTTPRequestDirector if not nil
This commit is contained in:
Marco Vidonis 2022-11-28 23:35:36 +00:00 committed by GitHub
parent 436af2580f
commit 916af6e38a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 46 additions and 30 deletions

View File

@ -102,6 +102,9 @@ type ClientConfig struct {
LookupTrackerIp func(*url.URL) ([]net.IP, error)
// HTTPUserAgent changes default UserAgent for HTTP requests
HTTPUserAgent string
// HTTPRequestDirector modifies the request before it's sent.
// Useful for adding authentication headers, for example
HTTPRequestDirector func(*http.Request) error
// Updated occasionally to when there's been some changes to client
// behaviour in case other clients are assuming anything of us. See also
// `bep20`.

View File

@ -80,6 +80,7 @@ type AnnounceOpt struct {
HostHeader string
ClientIp4 net.IP
ClientIp6 net.IP
HTTPRequestDirector func(*http.Request) error
}
type AnnounceRequest = udp.AnnounceRequest
@ -95,6 +96,15 @@ func (cl Client) Announce(ctx context.Context, ar AnnounceRequest, opt AnnounceO
if userAgent != "" {
req.Header.Set("User-Agent", userAgent)
}
if opt.HTTPRequestDirector != nil {
err = opt.HTTPRequestDirector(req)
if err != nil {
err = fmt.Errorf("error modifying HTTP request: %s", err)
return
}
}
req.Host = opt.HostHeader
resp, err := cl.hc.Do(req)
if err != nil {

View File

@ -39,6 +39,7 @@ type Announce struct {
Request AnnounceRequest
HostHeader string
HTTPProxy func(*http.Request) (*url.URL, error)
HTTPRequestDirector func(*http.Request) error
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
ListenPacket func(network, addr string) (net.PacketConn, error)
ServerName string
@ -83,5 +84,6 @@ func (me Announce) Do() (res AnnounceResponse, err error) {
HostHeader: me.HostHeader,
ClientIp4: me.ClientIp4.IP,
ClientIp6: me.ClientIp6.IP,
HTTPRequestDirector: me.HTTPRequestDirector,
})
}

View File

@ -158,6 +158,7 @@ func (me *trackerScraper) announce(ctx context.Context, event tracker.AnnounceEv
res, err := tracker.Announce{
Context: ctx,
HTTPProxy: me.t.cl.config.HTTPProxy,
HTTPRequestDirector: me.t.cl.config.HTTPRequestDirector,
DialContext: me.t.cl.config.TrackerDialContext,
ListenPacket: me.t.cl.config.TrackerListenPacket,
UserAgent: me.t.cl.config.HTTPUserAgent,