// Expense Tracker -- one program with several commands (starter). This file, // serve.go and the tests are finished. The TODOs are in commands.go, client.go, // and the packages under internal/. // // expenses serve starts the web server (the page and the JSON API) // expenses add adds an expense through the API // expenses list lists expenses through the API // expenses report shows totals through the API // expenses delete deletes an expense through the API // expenses version prints the version // // Run from the module folder: // // cd projects/09-expense-tracker/starter // go run ./cmd/expenses serve package main import ( "context" "fmt" "io" "os" "os/signal" ) // version is set when building: // // go build -ldflags "-X main.version=1.0.0" -o expenses.exe ./cmd/expenses var version = "dev" const usage = `Usage: expenses serve [-addr host:port] [-file name] [-log-format text|json] [-log-level level] expenses add [-addr host:port] [-date 2026-11-25] -category name [-note text] amount expenses list [-addr host:port] [-month 2026-11] expenses report [-addr host:port] [-month 2026-11] expenses delete [-addr host:port] id expenses version -addr is where the server listens, or where the other commands find it. It comes from the environment variable EXPENSES_ADDR, or else localhost:8080. Run "expenses -h" to see the flags of one command.` func main() { // Ctrl+C cancels ctx. The server then shuts down, and a request that is // waiting for an answer gives up. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) err := run(ctx, os.Args[1:], os.Stdout) stop() if err != nil { fmt.Fprintln(os.Stderr, "expenses:", err) os.Exit(1) } } // run picks the command. It writes normal output to out, and returns an error // instead of printing it, so that main is the one place that handles errors. func run(ctx context.Context, args []string, out io.Writer) error { if len(args) == 0 { return fmt.Errorf("no command given\n%s", usage) } command := args[0] rest := args[1:] switch command { case "serve": return runServe(ctx, rest) case "add": return runAdd(ctx, rest, out) case "list": return runList(ctx, rest, out) case "report": return runReport(ctx, rest, out) case "delete": return runDelete(ctx, rest, out) case "version": fmt.Fprintln(out, "expenses", version) return nil case "help", "-h", "-help", "--help": fmt.Fprintln(out, usage) return nil default: return fmt.Errorf("unknown command %q\n%s", command, usage) } } // envOr returns the environment variable called name, or fallback when it is // not set or is empty. func envOr(name string, fallback string) string { value, ok := os.LookupEnv(name) if !ok || value == "" { return fallback } return value } // defaultAddr is the default for every -addr flag. func defaultAddr() string { return envOr("EXPENSES_ADDR", "localhost:8080") }