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
+20.8k Golang : Saving private and public key to files
+12.8k Golang : Remove or trim extra comma from CSV
+21.6k Curl usage examples with Golang
+48k Golang : Convert int to byte array([]byte)
+6.7k Golang : Warp text string by number of characters or runes example
+24.8k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+7.5k Android Studio : How to detect camera, activate and capture example
+10.1k Golang : Get escape characters \u form from unicode characters
+9.7k Golang : Copy map(hash table) example
+10.2k Golang : How to tokenize source code with text/scanner package?
+10.3k Golang : How to get quoted string into another string?
+6.1k Golang : Experimenting with the Rejang script