Video Coming Soon...

Created by Zed A. Shaw Updated 2025-10-23 14:49:14

44: curl or wget

This exercise is pending. Quick notes about this exercise:

The Code

View Source file go-coreutils/curl/main.go Only

package main

import (
  "fmt"
  "net/http"
  "flag"
  "log"
  "os"
  "io"
  "path/filepath"
)

func main() {
  var save bool
  var headers bool

  flag.BoolVar(&save, "O", false, "output file to local disk")
  flag.BoolVar(&headers, "I", false, "inspect headers")
  flag.Parse()

  if flag.NArg() == 0 { log.Fatal("USAGE: curl [-O] [-I] URL") }

  target_url := flag.Args()[0]

  resp, err := http.Get(target_url)
  if err != nil { log.Fatal(err) }

  if headers {
    for key, values := range resp.Header {
      for _, val := range values {
        fmt.Printf("%s: %s\n", key, val)
      }
    }
  } else if save {
    output := filepath.Base(resp.Request.URL.Path)

    out, err := os.Create(output)
    if err != nil { log.Fatal(err) }

    io.Copy(out, resp.Body)
  } else { 
    io.Copy(os.Stdout, resp.Body)
  }
}
Previous Lesson Next Lesson

Register for Learn Go the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.