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
+30.7k Golang : Calculate percentage change of two values
+5.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+14.6k Golang : Basic authentication with .htpasswd file
+5.4k Golang : Detect words using using consecutive letters in a given string
+12.8k Swift : Convert (cast) Int to String ?
+7.3k Golang : Handling Yes No Quit query input
+9.6k Golang : Resumable upload to Google Drive(RESTful) example
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+15.8k Golang : Get sub string example
+5.9k Golang : Dealing with backquote
+10k Golang : How to profile or log time spend on execution?
+9.2k Golang : How to protect your source code from client, hosting company or hacker?