A worker command starts the worker component from a command-line interface, replacing environment-variable setup with explicit flags and making worker startup independent from manager startup. section 12.6 section 12.12
The command assembles a worker from a small set of responsibilities:
- Register workerCmd with the root command so the CLI exposes the worker operation. section 12.6
- Define host, port, name, and dbtype flags, with defaults for 0.0.0.0, 5556, a generated worker name, and memory storage. section 12.6
- Read flag values in Run, construct the worker and its API, then launch task processing, statistics collection, and task updates concurrently. section 12.6
- Start the API after logging its address, leaving the worker available to respond to manager requests about task state. section 12.6
Starting a configured worker
go run main.go worker --host 0.0.0.0 --port 5556 --name worker-1 --dbtype persistent starts the worker API and its background task loops. Running worker --help exposes the same configuration through Cobra's generated usage output. section 12.6
Listing 12.2 The skeleton worker command created by the cobra-cli add command
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// workerCmd represents the worker command
var workerCmd = &cobra.Command{
Use: "worker",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely
contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("worker called")
},
}
func init() {
rootCmd.AddCommand(workerCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// workerCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// workerCmd.Flags().BoolP("toggle", "t", false, "Help message for
toggle")
}
Inspect the generated Cobra skeleton to see the command definition, Run callback, initialization hook, and root-command registration before adding worker behavior. section 12.6
