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
+20k Golang : How to get struct tag and use field name to retrieve data?
+11.4k Swift : Convert (cast) Float to String
+33.8k Golang : Call a function after some delay(time.Sleep and Tick)
+10.6k Golang : Get currencies exchange rates example
+12.4k Golang : Forwarding a local port to a remote server example
+8.1k Prevent Write failed: Broken pipe problem during ssh session with screen command
+5.8k Unix/Linux : How to open tar.gz file ?
+5.1k Golang : Calculate half life decay example
+19.1k Golang : Delete item from slice based on index/key position
+22.8k Golang : Test file read write permission example
+25.3k Golang : convert rune to integer value
+14k Javascript : Prompt confirmation before exit