Skip to content

🌐 HTTP Download

pkg/composerutils/http.go provides file download functions with proxy and timeout control, commonly used to download Composer phar packages, package indexes, etc.

DownloadConfig

go
type DownloadConfig struct {
    UseProxy       bool
    ProxyURL       string
    TimeoutSeconds int
}
FieldTypeDescription
UseProxyboolWhether to enable proxy
ProxyURLstringProxy address (only effective when UseProxy=true)
TimeoutSecondsintTimeout seconds, default 60

DownloadFile

Downloads file from URL to local path, supports HTTP/HTTPS, proxy, timeout. Target file will be overwritten if exists.

go
func DownloadFile(sourceURL, destPath string, config DownloadConfig) error
ParameterTypeDescription
sourceURLstringDownload source URL
destPathstringLocal storage path
configDownloadConfigDownload config

Possible errors (all wrapped as ErrDownloadFailed):

  • Invalid URL format
  • Network connection failed
  • HTTP status code not 200
  • Local file creation/write failed
  • Timeout
go
var ErrDownloadFailed = errors.New("download failed")

Example

go
package main

import (
	"fmt"
	"github.com/scagogogo/composer-skills/pkg/composerutils"
)

func main() {
	// Direct download
	config := composerutils.DownloadConfig{UseProxy: false}
	err := composerutils.DownloadFile(
		"https://getcomposer.org/composer.phar",
		"/tmp/composer.phar",
		config,
	)
	if err != nil {
		fmt.Printf("Download failed: %v\n", err)
	}

	// Download large file using proxy
	proxyConfig := composerutils.DownloadConfig{
		UseProxy:       true,
		ProxyURL:       "http://proxy.example.com:8080",
		TimeoutSeconds: 120,
	}
	_ = composerutils.DownloadFile(
		"https://example.com/large-file.tar.gz",
		"/downloads/file.tar.gz",
		proxyConfig,
	)
}

Implementation Notes

  • Based on net/http standard client, cross-platform.
  • Proxy injected into http.Transport via http.ProxyURL.
  • Timeout controlled by http.Client.Timeout, default 60 seconds.

Difference from pkg/repository

repository.DownloadIndex is specifically for downloading Packagist package indexes; composerutils.DownloadFile is a general HTTP download utility that can download any URL. pkg/installer internally uses this capability when downloading composer phar.

Advanced

  • Mock download behavior see Mock Interfaces MockDownloadHelper.
  • Wrapper for actually downloading composer.phar see Installer.

Released under the MIT License