8 "github.com/anacrolix/log"
9 "github.com/anacrolix/torrent/bencode"
10 "github.com/anacrolix/torrent/metainfo"
13 // Add HTTP endpoints that serve the metainfo. They will be used if the torrent info isn't obtained
14 // yet. The Client HTTP client is used.
15 func (t *Torrent) UseSources(sources []string) {
23 for _, s := range sources {
24 _, loaded := t.activeSources.LoadOrStore(s, struct{}{})
30 err := t.useActiveTorrentSource(s)
31 _, loaded := t.activeSources.LoadAndDelete(s)
39 t.logger.Levelf(level, "used torrent source %q [err=%v]", s, err)
44 func (t *Torrent) useActiveTorrentSource(source string) error {
45 ctx, cancel := context.WithCancel(context.Background())
55 mi, err := getTorrentSource(ctx, source, t.cl.httpClient)
59 return t.MergeSpec(TorrentSpecFromMetaInfo(&mi))
62 func getTorrentSource(ctx context.Context, source string, hc *http.Client) (mi metainfo.MetaInfo, err error) {
64 if req, err = http.NewRequestWithContext(ctx, http.MethodGet, source, nil); err != nil {
67 var resp *http.Response
68 if resp, err = hc.Do(req); err != nil {
71 defer resp.Body.Close()
72 if resp.StatusCode != http.StatusOK {
73 err = fmt.Errorf("unexpected response status code: %v", resp.StatusCode)
76 err = bencode.NewDecoder(resp.Body).Decode(&mi)