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
+4.8k Golang : Use NLP to get sentences for each paragraph example
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+15.9k Golang : Check if IP address is version 4 or 6
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+7.9k Golang : How to extract video or image files from html source code
+14.8k Golang : Get sub string example
+17.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+11.4k Swift : Convert (cast) Int or int32 value to CGFloat
+21.2k Golang : Set and Get HTTP request headers example
+3k Golang : PGX CopyFrom to insert rows into Postgres database
+13.3k Golang : Convert(cast) int to float example
+6k Golang : Get Alexa ranking data example