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 Golang : Simple image viewer with Go-GTK
+7.5k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+9.9k Golang : Get current, epoch time and display by year, month and day
+19.2k Golang : Clearing slice
+9.5k Golang : Temperatures conversion example
+40.3k Golang : UDP client server read write example
+16.5k Golang : Find out mime type from bytes in buffer
+30.1k Golang : Get and Set User-Agent examples
+41.2k Golang : How to check if a string contains another sub-string?
+36.3k Golang : Integer is between a range
+10.7k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+11.8k Golang : Surveillance with web camera and OpenCV