Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dwango@5
package main
import (
"os"
"net/http"
"io"
"path/filepath"
"sync"
"github.com/codegangsta/cli"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
app := cli.NewApp()
app.Name = "downloader"
app.Usage = "hogehoge"
app.Action = func(c *cli.Context) {
var waitGroup sync.WaitGroup
for _, url := range c.Args() {
waitGroup.Add(1)
go Download(url, &waitGroup)
}
waitGroup.Wait()
}
app.Run(os.Args)
}
func Download(url string, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
_, fileName := filepath.Split(url)
downloader := NewDownloader(url, "/tmp/"+fileName)
downloader.Download()
}
type Downloader struct {
Uri string
SavePath string
}
func NewDownloader(uri string, savePath string) *Downloader {
return &Downloader{Uri: uri, SavePath: savePath}
}
func (d *Downloader) Download() error {
tmpFile, err := d.createTmpFile(d.SavePath)
if err != nil {
return err
}
defer tmpFile.Close()
response, err := d.request()
if err != nil {
return err
}
defer response.Body.Close()
return d.copyResponseToTmpFile(tmpFile, response)
}
func (d *Downloader) createTmpFile(path string) (*os.File, error) {
file, err := os.Create(path)
if err != nil {
return nil, err
}
return file, nil
}
func (d *Downloader) request() (*http.Response, error) {
response, err := http.Get(d.Uri)
if err != nil {
return nil, err
}
return response, err
}
func (d *Downloader) copyResponseToTmpFile(tmpFile *os.File, response *http.Response) (error) {
_, err := io.Copy(tmpFile, response.Body)
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment