golang using files code example
Example 1: golang read file
dat, err := ioutil.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))
Example 2: golang http save downloaded file
import (
"os"
"net/http"
"io"
)
func downloadFile(filepath string, url string) (err error) {
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}