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
+9.2k Golang : Simple client-server HMAC authentication without SSL example
+4.9k Golang : How to handle file size larger than available memory panic issue
+9.6k Golang : How to display image file or expose CSS, JS files from localhost?
+7.9k Golang : Get login name from environment and prompt for password
+27.6k Golang : Regular Expression for alphanumeric and underscore
+6.6k Golang : automatically figure out array length(size) with three dots
+7.9k Golang : Concatenate (combine) buffer data example
+13.9k Golang : delete and modify XML file content
+13.8k Golang : Capture stdout of a child process and act according to the result
+17.4k Golang : Append content to a file
+7.5k Android Studio : Checkbox for user to select options example
+4.5k CloudFlare : Another way to get visitor's real IP address