Learning GoLang: A Command-Line HTTP Client Tool to Grab URL Contents

in #programming5 years ago

GoLang provides HTTP client library. We can import the "net/http" to make a HTTP Get. Then we can use the bufio.NewScanner to print the content Line by Line or we can directly print out the content using fmt.Print(response.Body).

We can take a paramter of URL string at command line using the os.Args (which contains the program path).

If there is any error, we can throw errors using the panic function. And we can set return/exit code using os.Exit() function.

We can convert the status string into Integer using strconv.Atoi function. We can use the strings.Fields or strings.Split(str, delimier) to split a string by whitespaces.

Overall, the GoLang command line HTTP tool source code is as follows:

package main

import (
    "bufio"
    "fmt"
    "net/http"
    "os"
)

func main() {
    if len(os.Args) == 1 {
        panic("Need a URL parameter")
        os.Exit(1)
    }
    var url = os.Args[1]

    resp, err := http.Get(url)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    scanner := bufio.NewScanner(resp.Body)
    for i := 0; scanner.Scan(); i++ {
        fmt.Println(scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        panic(err)
    }

    //var v = strings.Fields(resp.Status)
    //intVar, err := strconv.Atoi(v[0])

    fmt.Println("Status = " + resp.Status)
    os.Exit(0)
}

Example usage:

$ go run url.go https://helloacm.com/api/phpver
"7.3.14-6+ubuntu18.04.1+deb.sury.org+1"
Status = 200 OK

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

  1. Voting Algorithm Updated to Favor those High Delegations!
  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.102
BTC 63861.21
ETH 1783.63
USDT 1.00
SBD 0.39