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
+22k Golang : Use TLS version 1.2 and enforce server security configuration over client
+4.9k Golang : A program that contain another program and executes it during run-time
+40.2k Golang : UDP client server read write example
+4.8k MariaDB/MySQL : Form select statement or search query with Chinese characters
+37.7k Golang : Comparing date or timestamp
+13.2k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+33.8k Golang : All update packages with go get command
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+26.8k Golang : Convert file content into array of bytes
+36.6k Golang : Validate IP address
+14.9k Golang : Submit web forms without browser by http.PostForm example
+6.9k Get Facebook friends working in same company