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
+15.4k Golang : read gzipped http response
+10.6k Golang : Change date format to yyyy-mm-dd
+5.7k Golang : Derive cryptographic key from passwords with Argon2
+10.5k Swift : Convert (cast) Float to String
+16.2k Golang : Parse date string and convert to dd-mm-yyyy format
+6.3k Golang : File system scanning
+5.9k Golang : constant 20013 overflows byte error message
+9.6k Golang : Get currencies exchange rates example
+25.2k Golang : Encrypt and decrypt data with AES crypto
+48.9k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+13.5k Golang : Get URI segments by number and assign as variable example
+12.6k Golang : unknown escape sequence error