FedP2P/webseed/request.go

41 lines
1022 B
Go
Raw Normal View History

2020-06-01 16:25:45 +08:00
package webseed
import (
"fmt"
"net/http"
"net/url"
2020-06-01 16:25:45 +08:00
"path"
"strings"
"github.com/anacrolix/torrent/metainfo"
)
2020-12-21 09:24:24 +08:00
func trailingPath(infoName string, pathComps []string) string {
return path.Join(
func() (ret []string) {
for _, comp := range append([]string{infoName}, pathComps...) {
ret = append(ret, url.QueryEscape(comp))
}
return
}()...,
)
}
2020-06-01 16:25:45 +08:00
// Creates a request per BEP 19.
func NewRequest(url_ string, fileIndex int, info *metainfo.Info, offset, length int64) (*http.Request, error) {
2020-06-01 16:25:45 +08:00
fileInfo := info.UpvertedFiles()[fileIndex]
if strings.HasSuffix(url_, "/") {
// BEP specifies that we append the file path. We need to escape each component of the path
// for things like spaces and '#'.
2020-12-21 09:24:24 +08:00
url_ += trailingPath(info.Name, fileInfo.Path)
2020-06-01 16:25:45 +08:00
}
req, err := http.NewRequest(http.MethodGet, url_, nil)
2020-06-01 16:25:45 +08:00
if err != nil {
return nil, err
}
if offset != 0 || length != fileInfo.Length {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
}
return req, nil
}