Learning GoLang: A Command-Line HTTP Client Tool to Grab URL Contents
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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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