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
+7.1k Golang : Gorrila mux.Vars() function example
+5.8k Golang : Detect variable or constant type
+7.7k Golang : Reverse a string with unicode
+7.3k Golang : Accessing dataframe-go element by row, column and name example
+6k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+20.1k Golang : Convert seconds to human readable time format example
+5.5k PHP : Fix Call to undefined function curl_init() error
+10.1k Golang : Compare files modify date example
+5.2k Golang : Calculate half life decay example
+6.2k Golang & Javascript : How to save cropped image to file on server
+14.1k Golang : syscall.Socket example
+13k Golang : List objects in AWS S3 bucket