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
+6.2k nginx : force all pages to be SSL
+5.8k Golang : Error handling methods
+14.2k Golang : convert rune to unicode hexadecimal value and back to rune character
+4.9k Linux/MacOSX : How to symlink a file?
+17.9k Golang : delete and modify XML file content
+14.7k Golang : Rename directory
+20.1k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+26.4k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+12.3k Golang : Save webcamera frames to video file
+10.8k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+10.3k Golang : Find and replace data in all files recursively
+20.6k Golang : How to get own program name during runtime ?