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
+28k Golang : missing Git command
+28.7k Get client IP Address in Go
+5.2k Golang : Process non-XML/JSON formatted ASCII text file example
+11.5k Golang : Get terminal width and height example
+6.3k Golang : Process json data with Jason package
+5.7k Golang : Muxing with Martini example
+6.6k Golang : Convert(cast) io.Reader type to string
+25.3k Golang : Force your program to run with root permissions
+16.1k Golang : Qt image viewer example
+18.5k Golang : Append content to a file
+17.8k Golang : How to make function callback or pass value from function as parameter?
+13.1k Golang : How to determine if user agent is a mobile device example