]> Sergey Matveev's repositories - btrtrc.git/blob - webseed/request.go
6d62ccb61355dc83bd05008ad231a31c472ff97f
[btrtrc.git] / webseed / request.go
1 package webseed
2
3 import (
4         "fmt"
5         "net/http"
6         "net/url"
7         "path"
8         "strings"
9
10         "github.com/anacrolix/torrent/metainfo"
11 )
12
13 func trailingPath(infoName string, pathComps []string) string {
14         return path.Join(
15                 func() (ret []string) {
16                         for _, comp := range append([]string{infoName}, pathComps...) {
17                                 ret = append(ret, url.QueryEscape(comp))
18                         }
19                         return
20                 }()...,
21         )
22 }
23
24 // Creates a request per BEP 19.
25 func NewRequest(url_ string, fileIndex int, info *metainfo.Info, offset, length int64) (*http.Request, error) {
26         fileInfo := info.UpvertedFiles()[fileIndex]
27         if strings.HasSuffix(url_, "/") {
28                 // BEP specifies that we append the file path. We need to escape each component of the path
29                 // for things like spaces and '#'.
30                 url_ += trailingPath(info.Name, fileInfo.Path)
31         }
32         req, err := http.NewRequest(http.MethodGet, url_, nil)
33         if err != nil {
34                 return nil, err
35         }
36         if offset != 0 || length != fileInfo.Length {
37                 req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
38         }
39         return req, nil
40 }