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
+12.3k Golang : Exit, terminating or aborting a program
+50.5k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+14.3k Golang : Convert(cast) int to float example
+23k Golang : Print out struct values in string format
+15.2k Golang : Force download file example
+12.7k Python : Convert IPv6 address to decimal and back to IPv6
+9.2k Golang : Convert(cast) string to int64
+11.7k Golang : Convert decimal number(integer) to IPv4 address
+10.3k Golang : Create matrix with Gonum Matrix package example
+21k Golang : How to get time zone and load different time zone?
+23.8k Golang : Find biggest/largest number in array
+8.5k Golang : Gorilla web tool kit schema example