You can create hierarchical commands by providing a slice of SubCommandOptions to the SubCommand property of CommandOptions.
Behavioral Rules:
- Handler Priority: If a top-level command has subcommands, the top-level
HandlerFunc is ignored. SugarDB will attempt to match the second element of the command string against the registered subcommands. - Subcommand Matching: If a subcommand is not found, an error is returned.
- Independence: While subcommands can share handlers, it is best practice for each subcommand to provide its own unique
KeyExtractionFunc and HandlerFunc.
// Define the subcommands
subCommands := []db.SubCommandOptions{
{
Command: "SUB1",
Module: "mymodule",
Categories: []string{"subcategory1"},
Description: "This is subcommand 1",
Sync: false,
KeyExtractionFunc: mySubCommandKeyExtractionFunc,
HandlerFunc: mySubCommandHandler,
},
{
Command: "SUB2",
Module: "mymodule",
Categories: []string{"subcategory2"},
Description: "This is subcommand 2",
Sync: true,
KeyExtractionFunc: mySubCommandKeyExtractionFunc,
HandlerFunc: mySubCommandHandler,
},
}
// Define the main command options
command := db.CommandOptions{
Command: "MYCOMMAND",
Module: "mymodule",
Categories: []string{"category1"},
Description: "This is a sample command with subcommands",
Sync: true,
SubCommand: subCommands,
}
err := server.AddCommand(command)