]> Sergey Matveev's repositories - btrtrc.git/blob - webseed/request.go
Merge branch 'http-proxying' into crawshaw
[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 // Escapes path name components suitable for appending to a webseed URL. This works for converting
14 // S3 object keys to URLs too.
15 func EscapePath(pathComps []string) string {
16         return path.Join(
17                 func() (ret []string) {
18                         for _, comp := range pathComps {
19                                 ret = append(ret, url.QueryEscape(comp))
20                         }
21                         return
22                 }()...,
23         )
24 }
25
26 func trailingPath(infoName string, fileComps []string) string {
27         return EscapePath(append([]string{infoName}, fileComps...))
28 }
29
30 // Creates a request per BEP 19.
31 func NewRequest(url_ string, fileIndex int, info *metainfo.Info, offset, length int64) (*http.Request, error) {
32         fileInfo := info.UpvertedFiles()[fileIndex]
33         if strings.HasSuffix(url_, "/") {
34                 // BEP specifies that we append the file path. We need to escape each component of the path
35                 // for things like spaces and '#'.
36                 url_ += trailingPath(info.Name, fileInfo.Path)
37         }
38         req, err := http.NewRequest(http.MethodGet, url_, nil)
39         if err != nil {
40                 return nil, err
41         }
42         if offset != 0 || length != fileInfo.Length {
43                 req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
44         }
45         return req, nil
46 }