LoginSignup
16
13

More than 5 years have passed since last update.

go言語でイメージ画像をダウンロードするツールを作る

Last updated at Posted at 2014-12-28

標準入力から受け取ったURLをダウンロードして、保存するツールを作る

コード

downloadImage.go
package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "os"
  "path"
)

func main() {
  var url string = os.Args[1]
  response, err := http.Get(url)

  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  fmt.Println("status:", response.Status)

  body, err := ioutil.ReadAll(response.Body)

  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  _, filename := path.Split(url)

  file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0666)

  if err != nil {
    fmt.Println(err)
  }

  defer func() {
    file.Close()
  }()

  file.Write(body)
}

メモ

  • path.Splitした値を、dir, filenameで受けていたが、dirは使わないため、declared and not usedがでた。こういうときは_に入れるらしい。

参考:Go言語でインターネットから画像をダウンロードする方法

16
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13