pdf Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/pdf/ Sat, 26 Sep 2020 05:38:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 pdf Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/pdf/ 32 32 159787465 Download an image or file from a URL in Go (Golang) https://vikasboss.github.io/download-image-file-url-golang/ https://vikasboss.github.io/download-image-file-url-golang/#respond Fri, 21 Feb 2020 14:15:16 +0000 https://vikasboss.github.io/?p=1411 Overview Below are the steps to download an image or a file from a URL use http.Get(URL) function to get the bytes of the file from the URL. Create an empty file...

The post Download an image or file from a URL in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

Below are the steps to download an image or a file from a URL

  • use http.Get(URL) function to get the bytes of the file from the URL.
  • Create an empty file using os.Create() function
  • Use io.Copy() function to copy the downloaded bytes to the file created in step 2

Code

package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	fileName := "sample.pdf"
	URL := "http://www.africau.edu/images/default/sample.pdf"
	err := downloadFile(URL, fileName)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("File %s downlaod in current working directory", fileName)
}

func downloadFile(URL, fileName string) error {
	//Get the response bytes from the url
	response, err := http.Get(URL)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		return errors.New("Received non 200 response code")
	}
	//Create a empty file
	file, err := os.Create(fileName)
	if err != nil {
		return err
	}
	defer file.Close()

	//Write the bytes to the fiel
	_, err = io.Copy(file, response.Body)
	if err != nil {
		return err
	}

	return nil
}

Output:

File sample.pdf downlaod in current working directory

The post Download an image or file from a URL in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/download-image-file-url-golang/feed/ 0 1411