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.3k Fix fatal error: evacuation not done in time problem
+6.1k Golang : Handle Palindrome string with case sensitivity and unicode
+4.8k Golang : How to validate ISBN?
+36.7k Golang : How to iterate over a []string(array)
+7.8k Golang : cannot assign type int to value (type uint8) in range error
+8k Golang : Underscore string example
+5.7k Golang : Sort words with first uppercase letter
+5.3k Javascript : Push notifications to browser with Push.js
+4k How to check with curl if my website or the asset is gzipped ?
+5.8k Golang : Get all countries phone codes
+4.6k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+15.4k Golang : Get current URL example