Structuring a Go CLI that fetches a URL
basic Go CLI, HTTP, and error handling.
parse args with the flag package, http.Get the URL, check err and status, defer resp.Body.Close, copy body to stdout, exit non-zero on failure.
WHAT THIS TESTS Whether you can structure a small idiomatic Go program that parses input, performs network IO, and handles errors explicitly, including resource cleanup.
A GOOD ANSWER COVERS In main, declare flags with the flag package, for example a timeout flag via flag.Duration, then call flag.Parse, and read the positional URL from flag.Arg(0), validating that one was provided. Build the request: the simplest path is http.Get(url), or construct an http.Client with a timeout and call client.Get for production-quality behavior. Always check the returned error first and bail out on failure. On success, immediately defer resp.Body.Close() so the connection is released and can be reused; failing to close leaks file descriptors and connections. Inspect resp.StatusCode if you want to treat non-2xx as an error. To print the content, stream it with io.Copy(os.Stdout, resp.Body) rather than reading it all into memory. For errors, write a message to os.Stderr and call os.Exit with a non-zero code, or keep a run function returning error and let main translate that to an exit code.
COMMON WRONG ANSWERS Ignoring errors with the blank identifier. Forgetting defer resp.Body.Close, leaking connections. Using ioutil.ReadAll to slurp huge bodies into memory unnecessarily. Not setting a client timeout, so a hung server blocks forever. Calling os.Exit inside helpers, which skips deferred cleanup.
LIKELY FOLLOW-UPS Why set a timeout, and how does context.WithTimeout integrate via http.NewRequestWithContext? How do you handle redirects and non-2xx responses? Why prefer returning errors over panicking? How would you add retries or stream to a file?
ONE CONCRETE EXAMPLE flag.Parse(); url := flag.Arg(0); resp, err := http.Get(url); if err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) }; defer resp.Body.Close(); io.Copy(os.Stdout, resp.Body). This fetches the URL, prints its body, closes the connection, and reports failures on stderr with a non-zero exit, which is the expected shape.
Read the original → pkg.go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.