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
+6.4k Golang : Extract sub-strings
+5.6k Golang *File points to a file or directory ?
+11.8k Golang : Find age or leap age from date of birth example
+17.4k Golang : Find file size(disk usage) with filepath.Walk
+7.1k Golang : Levenshtein distance example
+18.1k Golang : Simple client server example
+10.1k Golang : Check if user agent is a robot or crawler example
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+12.5k Golang : Search and extract certain XML data example
+14.5k Golang : How to shuffle elements in array or slice?
+5.9k Javascript : How to replace HTML inside <div>?
+41.4k Golang : How to count duplicate items in slice/array?