Browse Source

Wrote image downloader function

master
grumbulon 6 months ago
parent
commit
b8be2a4eb0
  1. 37
      downloader.go
  2. 2
      main.go

37
downloader.go

@ -2,10 +2,15 @@ package main
import (
"database/sql"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
)
func download() {
func getFiles() {
//fileName := "image.png"
var urls []string
@ -26,5 +31,33 @@ func download() {
row.Scan(&url)
urls = append(urls, url)
}
log.Println(urls)
for i := 0; i < len(urls); i++ {
filename := fmt.Sprintf("assets/image%d.png", i)
downloadFiles(urls[i], filename)
}
}
func downloadFiles(URL, fileName string) {
response, err := http.Get(URL)
if err != nil {
log.Fatalln(err)
}
defer response.Body.Close()
if response.StatusCode != 200 {
log.Fatalln(errors.New("Failed to recieve 200 resp code"))
}
file, err := os.Create(fileName)
if err != nil {
log.Fatalln(err)
}
defer file.Close()
_, err = io.Copy(file, response.Body)
if err != nil {
log.Fatalln(err)
}
}

2
main.go

@ -46,6 +46,6 @@ func run(subreddit string) (err error) {
for i := 0; i < 5; i++ {
insert(db, posts[i])
}
download()
getFiles()
return
}