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
+11.3k Use systeminfo to find out installed Windows Hotfix(s) or updates
+19.5k Golang : Get current URL example
+8.5k Golang : Another camera capture GUI application with GTK and OpenCV
+21.6k SSL : How to check if current certificate is sha1 or sha2
+29.1k Golang : missing Git command
+5.6k List of Golang XML tutorials
+5.8k Golang : Use NLP to get sentences for each paragraph example
+5.7k Golang : Error handling methods
+11.6k How to tell if a binary(executable) file or web application is built with Golang?
+10.3k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+4.9k Golang : Calculate a pip value and distance to target profit example
+7.7k Golang : Scan files for certain pattern and rename part of the files