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.7k Golang : Populate slice with sequential integers example
+11.1k Golang : Web routing/multiplex example
+6k Unix/Linux : How to open tar.gz file ?
+16.4k Golang : How to extract links from web page ?
+11.6k Swift : Convert (cast) Float to String
+5.4k PHP : Hide PHP version information from curl
+27.5k Golang : Convert CSV data to JSON format and save to file
+7.2k Golang : Array mapping with Interface
+12.5k Golang : How to check if a string starts or ends with certain characters or words?
+5.5k Golang : Display advertisement images or strings on random order
+21.8k Golang : GORM create record or insert new record into database example
+8.4k Golang : Oanda bot with Telegram and RSI example