Go, also known as Golang, is an efficient language for building command-line applications. The simplicity and performance of Go make it a popular choice for developers. Below are three practical examples that demonstrate how to implement command-line applications using Go.
In many scenarios, you may need to read the contents of a file and output it to the console. This simple command-line application takes a filename as an argument and prints its contents.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide a filename.")
return
}
file, err := os.Open(os.Args[1])
if err != nil {
fmt.Printf("Error opening file: %s\n", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Printf("Error reading file: %s\n", err)
}
}
bufio
package is used for efficient reading of the file.A basic calculator is a perfect example of a command-line application that performs arithmetic operations based on user input. This application accepts two numbers and an operator as arguments and outputs the result.
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) != 4 {
fmt.Println("Usage: go run main.go <num1> <operator> <num2>")
return
}
num1 := os.Args[1]
operator := os.Args[2]
num2 := os.Args[3]
result, err := calculate(num1, operator, num2)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Result: %v\n", result)
}
func calculate(num1Str, operator, num2Str string) (float64, error) {
var num1, num2 float64
var err error
num1, err = strconv.ParseFloat(num1Str, 64)
if err != nil {
return 0, fmt.Errorf("Invalid number: %s", num1Str)
}
num2, err = strconv.ParseFloat(num2Str, 64)
if err != nil {
return 0, fmt.Errorf("Invalid number: %s", num2Str)
}
switch operator {
case "+":
return num1 + num2, nil
case "-":
return num1 - num2, nil
case "*":
return num1 * num2, nil
case "/":
if num2 == 0 {
return 0, fmt.Errorf("Cannot divide by zero")
}
return num1 / num2, nil
default:
return 0, fmt.Errorf("Unsupported operator: %s", operator)
}
}
An HTTP client command-line tool can be useful for fetching and displaying data from a web API. This application takes a URL as an argument and retrieves JSON data from it.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide a URL.")
return
}
url := os.Args[1]
response, err := http.Get(url)
if err != nil {
fmt.Printf("Error fetching data: %s\n", err)
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("Error reading response: %s\n", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(body, &data); err != nil {
fmt.Printf("Error parsing JSON: %s\n", err)
return
}
fmt.Printf("Fetched data: %v\n", data)
}