Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kadai3-2: lfcd85 #33

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Implement minimum download function
lfcd85 committed Jun 19, 2019
commit 95c864d1675f06419a4cd653f07f9d14390ff3bd
16 changes: 15 additions & 1 deletion kadai3-2/lfcd85/cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
package main

import (
"fmt"
"net/url"

"github.com/gopherdojo/dojo5/kadai3-2/lfcd85/mypget"
)

func main() {
mypget.Execute()
// FIXME: get URL from option
url, err := url.Parse("https://golang.org/doc/gopher/frontpage.png")
if err != nil {
fmt.Println(err)
return
}

err = mypget.New(url).Execute()
if err != nil {
fmt.Println(err)
return
}
}
41 changes: 40 additions & 1 deletion kadai3-2/lfcd85/mypget/mypget.go
Original file line number Diff line number Diff line change
@@ -2,8 +2,47 @@ package mypget

import (
"fmt"
"io"
"net/http"
"net/url"
"os"
)

func Execute() {
type Downloader struct {
url *url.URL
}

func New(url *url.URL) *Downloader {
return &Downloader{
url: url,
}
}

func (d *Downloader) Execute() error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

せっかくなので引数にcontext.Contextとって、nilならBackgroundにしても良いかも。

fmt.Println("Hello, split downloader!")
err := d.Download()
return err
}

func (d *Downloader) Download() error {
req, err := http.NewRequest("GET", d.url.String(), nil)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

http.MethodGet

if err != nil {
return err
}

resp, err := http.DefaultClient.Do(req)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HTTPクライアントを変更できるようにしておくとよいかも。
最近はあんまり必要ないかもしれないけど、GAEだと特殊なHTTPクライアントを使う必要があったりするので。

if err != nil {
return err
}
defer resp.Body.Close()

// FIXME: create proper directory for downloading
f, err := os.Create("./output.jpg")
if err != nil {
return err
}
defer f.Close()

_, err = io.Copy(f, resp.Body)
return err
}