Go Command-Line Application Examples
Examples of Implementing a Go Command-Line Application
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.
Example 1: Simple File Reader
Context
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)
}
}
Notes
- This program requires a filename to be passed as a command-line argument.
- The
bufiopackage is used for efficient reading of the file. - Variations could include implementing flags for line numbers or searching for specific words in the file.
Example 2: Basic Calculator
Context
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)
}
}
Notes
- This program performs basic arithmetic operations: addition, subtraction, multiplication, and division.
- The user inputs two numbers and an operator as command-line arguments.
- Extensions could include support for more complex operations, like exponentiation or square roots.
Example 3: HTTP Client to Fetch Data
Context
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)
}
Notes
- This program retrieves data from the specified URL and prints the JSON response.
- Make sure to handle various HTTP status codes and errors appropriately.
- Variations could include adding options for custom headers or query parameters.
Related Topics
Explore More Go Code Snippets
Discover more examples and insights in this category.
View All Go Code Snippets