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.8k Curl usage examples with Golang
+4.9k Golang : Struct field tags and what is their purpose?
+6.2k Nginx : How to block user agent ?
+5.5k Android Studio : Hello World example
+6.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+13.1k Golang : How to get URL port?
+21k Golang : Repeat a character by multiple of x factor
+10.1k How to test Facebook App on localhost ?
+3.7k MariaDB/MySQL : How to get version information
+10.4k Golang : Secure file deletion with wipe example
+4.1k Golang : Convert lines of string into list for delete and insert operation
+18.1k Mac OSX : Homebrew and Golang