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
+12.4k Golang : Print UTF-8 fonts on image example
+7.2k Golang : Validate credit card example
+8.1k Golang : Trim everything onward after a word
+24.1k Golang : Use regular expression to validate domain name
+18.6k Golang : Example for RSA package functions
+12.1k Golang : Determine if time variables have same calendar day
+31.7k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+22.8k Generate checksum for a file in Go
+8.4k Golang : Oanda bot with Telegram and RSI example
+17k Golang : How to generate QR codes?
+18.4k Golang : Put UTF8 text on OpenCV video capture image frame
+15.4k Golang : Get HTTP protocol version example