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
+33.3k Golang : All update packages with go get command
+11.4k Get form post value in Go
+20.1k Android Studio : AlertDialog and EditText to get user string input example
+8.2k Golang : Generate Datamatrix barcode
+6.3k Golang : Embedded or data bundling example
+10.6k Golang : Get UDP client IP address and differentiate clients by port number
+8.9k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+47.6k Golang : How to convert JSON string to map and slice
+8.8k Golang : Capture text return from exec function example
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+22.6k Golang : Calculate time different
+6.7k Golang : constant 20013 overflows byte error message