Golang : Save(pipe) HTTP response into a file
Problem :
You want to save or pipe a website content via http.Get()
function to a file for processing.
Solution :
Read the http response and save the body into a file via io.Copy()
function. For example :
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
response, err := http.Get("https://www.socketloop.com")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer response.Body.Close()
htmlfile, err := os.Create("file.html")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer htmlfile.Close()
// save response body into a file
io.Copy(htmlfile, response.Body)
fmt.Println("HTML data saved into file.html")
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.1k Golang : Get host name or domain name from IP address
+5.5k Fix fatal error: evacuation not done in time problem
+6.5k Golang : How to determine if request or crawl is from Google robots
+6.4k Golang : Calculate diameter, circumference, area, sphere surface and volume
+9.3k Golang : Scramble and unscramble text message by randomly replacing words
+6.6k Golang : Humanize and Titleize functions
+4.5k Linux : sudo yum updates not working
+13.5k Golang : Image to ASCII art example
+13.3k Golang : Read XML elements data with xml.CharData example
+51.7k Golang : How to get time in milliseconds?
+16.3k Golang : How to implement two-factor authentication?
+15.4k Golang : rune literal not terminated error