Master Go’s flag Package: Build a Weather CLI Tool in Minutes
This article explains how to use Go's standard flag library to create a command‑line tool that accepts a city name and displays the current weather by fetching and converting HTML data into terminal‑friendly output.
Understanding the flag Package
The Go standard library flag package parses command‑line options, supporting string, integer, and boolean flags. You can define flags with functions such as flag.String(), flag.Int(), and flag.Bool(), or bind them directly to variables using the Var variants.
import "flag"
var nFlag = flag.Int("n", 1234, "help message for flag n") var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}Using FlagSet
A FlagSet groups related flags. The default command‑line set is created as:
var CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)When parsing, you call flag.Parse() and then access the flag values directly.
Simple Example
package main
import (
"fmt"
"flag"
)
var (
intflag int
boolflag bool
stringflag string
)
func init() {
flag.IntVar(&intflag, "intflag", 0, "int flag value")
flag.BoolVar(&boolflag, "boolflag", false, "bool flag value")
flag.StringVar(&stringflag, "stringflag", "default", "string flag value")
}
func main() {
flag.Parse()
fmt.Println("int flag:", intflag)
fmt.Println("bool flag:", boolflag)
fmt.Println("string flag:", stringflag)
}Running the program:
$ ./main -intflag 12 -boolflag 1 -stringflag test
int flag: 12
bool flag: true
string flag: testRequirement: Weather Flag
The goal is a weather flag that receives a city name and prints its weather. The flag is defined with StringVar and parsed using a custom FlagSet:
type arguments struct { weatherCity string }
func (a *arguments) parseArgs(args []string) error {
f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
f.StringVar(&a.weatherCity, "weather", "", "check weather")
f.Usage = func() {
fmt.Fprintf(os.Stderr, "flags: %s", os.Args[0])
f.PrintDefaults()
os.Exit(1)
}
return f.Parse(args[1:])
}Fetching Weather Data
A simple http.Get retrieves the HTML page from wttr.in:
func getWeatherData(city string) (string, error) {
url := "https://wttr.in/" + city
resp, err := http.Get(url)
if err != nil { return "", err }
body, err := io.ReadAll(resp.Body)
if err != nil { return "", err }
return string(body), nil
}Converting HTML to Terminal Output
The HTML is turned into markdown with github.com/JohannesKaufmann/html-to-markdown and then rendered for the terminal using github.com/MichaelMure/go-term-markdown:
func GetWeather(city string) (string, error) {
url := "https://wttr.in/" + city
resp, err := http.Get(url)
if err != nil { return "", err }
data, err := io.ReadAll(resp.Body)
if err != nil { return "", err }
md := getMD(string(data))
result := markdown.Render(md, 280, 6)
return string(result), nil
}
func getMD(html string) string {
conv := md.NewConverter("", true, nil)
markdown, err := conv.ConvertString(html)
if err != nil { return "" }
return markdown
}Putting It All Together
In the main execution flow, after parsing arguments, call GetWeather and print the result:
if args.weatherCity != "" {
out, err := GetWeather(args.weatherCity)
if err != nil { fmt.Println(err); return }
fmt.Println(out)
}Running the completed tool:
$ opb -weather beijing
[terminal‑rendered weather information]Conclusion
The guide demonstrates the basics of Go’s flag handling, how to bind a city name to a flag, fetch remote HTML weather data, convert it to a readable terminal format, and assemble a functional CLI weather utility.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
