docs/advanced-guide/building-cli-applications/page.md
GoFr provides a simple way to build command-line applications using app.NewCMD(). This creates standalone CLI tools without starting an HTTP server.
To configure logging for CLI applications, set the following environment variable:
CMD_LOGS_FILE: The file path where CLI logs will be written. If not set, logs are discarded.Create a basic CLI application with subcommands:
package main
import (
"fmt"
"gofr.dev/pkg/gofr"
)
func main() {
app := gofr.NewCMD()
// Simple hello command
app.SubCommand("hello", func(c *gofr.Context) (any, error) {
return "Hello World!", nil
}, gofr.AddDescription("Print hello message"))
// Command with parameters
app.SubCommand("greet", func(c *gofr.Context) (any, error) {
name := c.Param("name")
if name == "" {
name = "World"
}
return fmt.Sprintf("Hello, %s!", name), nil
})
app.Run()
}
app.NewCMD(): Initialize a CLI applicationapp.SubCommand(name, handler, options...): Add a subcommandgofr.AddDescription(desc): Add help descriptiongofr.AddHelp(help): Add detailed help textctx.Param(name): Get command parametersctx.Out.Println(): Print to stdoutctx.Logger: Access loggingBuild and run your CLI:
go build -o mycli
./mycli hello
./mycli greet --name John
./mycli --help
# Basic command
./mycli hello
# Output: Hello World!
# Command with parameter
./mycli greet --name Alice
# Output: Hello, Alice!
# Help
./mycli --help
For more details, see the sample-cmd example.