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
+15k Golang : Delete certain files in a directory
+5.3k Clean up Visual Studio For Mac installation failed disk full problem
+7k Golang : File system scanning
+9.4k Golang : Qt get screen resolution and display on center example
+16.2k Golang : Read integer from file into array
+6.1k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+8.7k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+30.4k Golang : Download file example
+27.7k Golang : Move file to another directory
+18.5k Golang : Padding data for encryption and un-padding data for decryption
+11.8k Golang : Get remaining text such as id or filename after last segment in URL path