nativehttp

Simple interface to the native http client
Log | Files | Refs | README | LICENSE

main.go (743B)


      1 package main
      2 
      3 import (
      4 	"errors"
      5 	"io"
      6 	"os"
      7 
      8 	"git.sr.ht/~jackmordaunt/nativehttp"
      9 )
     10 
     11 func main() {
     12 	var (
     13 		uri  string = "https://www.example.com"
     14 		file string = "file.html"
     15 	)
     16 
     17 	if len(os.Args) > 1 {
     18 		uri = os.Args[1]
     19 	}
     20 	if len(os.Args) > 2 {
     21 		file = os.Args[2]
     22 	}
     23 
     24 	if err := downloadFile(uri, file); err != nil {
     25 		print("error: %v\n", err)
     26 	}
     27 }
     28 
     29 func downloadFile(url, file string) (err error) {
     30 	r, err := nativehttp.Get(url)
     31 	if err != nil {
     32 		return err
     33 	}
     34 
     35 	defer func() {
     36 		if e := r.Close(); e != nil {
     37 			err = errors.Join(err, e)
     38 		}
     39 	}()
     40 
     41 	f, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR, 0o644)
     42 	if err != nil {
     43 		return err
     44 	}
     45 
     46 	defer f.Close()
     47 
     48 	if _, err := io.Copy(f, r); err != nil {
     49 		return err
     50 	}
     51 
     52 	return nil
     53 }