···4848 chunk.ChunkSize = chunkSize
4949 chunk.RestartDownloads = restartDownloads
5050 chunk.ProgressDir = progressDir
5151+ chunk.UserAgent = userAgent
5152 prog := newProgress()
5253 for status := range chunk.Download(args...) {
5354 if status.Error != nil {
···6970 waitBetweenRetries time.Duration
7071 restartDownloads bool
7172 progressDir string
7373+ userAgent string
7274)
73757476func init() {
···8688 "",
8789 fmt.Sprintf("directory where to track progress; %s under user's home directory if blank, or CHUNK_DIR environment variable", chunk.DefaultChunkDir),
8890 )
9191+ rootCmd.Flags().StringVarP(&userAgent, "user-agent", "u", chunk.DefaultUserAgent, "user agent to use in HTTP requests")
8992}
90939194func main() {
+11
downloader.go
···2222 DefaultChunkSize = 8192
2323 DefaultWaitRetry = 1 * time.Second
2424 DefaultRestartDownload = false
2525+ DefaultUserAgent = ""
2526)
26272728// DownloadStatus is the data propagated via the channel sent back to the user
···99100 // ProgressDir is the directory where Chunk keeps track of each chunk
100101 // downloaded of each file.
101102 ProgressDir string
103103+104104+ // UserAgent is the user agent used for all requests. If not set, no
105105+ // user agent is sent.
106106+ UserAgent string
102107}
103108104109type chunk struct{ start, end int64 }
···110115 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
111116 if err != nil {
112117 return nil, fmt.Errorf("error creating the request for %s: %w", u, err)
118118+ }
119119+ if d.UserAgent != "" {
120120+ req.Header.Set("User-Agent", d.UserAgent)
113121 }
114122 req.Header.Set("Range", c.rangeHeader())
115123 resp, err := d.Client.Do(req)
···162170 req, err := http.NewRequestWithContext(ctx, http.MethodHead, u, nil)
163171 if err != nil {
164172 return fmt.Errorf("creating the request for %s: %w", u, err)
173173+ }
174174+ if d.UserAgent != "" {
175175+ req.Header.Add("User-Agent", d.UserAgent)
165176 }
166177 resp, err := d.Client.Do(req)
167178 if err != nil {
+15
downloader_test.go
···299299 }
300300}
301301302302+func TestGetDownload_WithUserAgent(t *testing.T) {
303303+ ua := "Answer/42.0"
304304+ s := httptest.NewServer(http.HandlerFunc(
305305+ func(w http.ResponseWriter, r *http.Request) {
306306+ if r.UserAgent() != ua {
307307+ t.Errorf("expected user-agent to be %s, got %s", ua, r.UserAgent())
308308+ }
309309+ },
310310+ ))
311311+ defer s.Close()
312312+ d := DefaultDownloader()
313313+ d.UserAgent = ua
314314+ <-d.Download(s.URL)
315315+}
316316+302317func TestGetDownloadSize_ContentLength(t *testing.T) {
303318 s := httptest.NewServer(http.HandlerFunc(
304319 func(w http.ResponseWriter, r *http.Request) {