How to have a raw parameter value in cobra?

82 views
Skip to first unread message

David Karr

unread,
Feb 25, 2024, 1:43:02 PMFeb 25
to golang-nuts
I am not a new programmer, but I am pretty new to golang, having only written a couple of small applications, and that was several months ago. I'm trying to construct an application using Cobra, using some nonstandard conventions. Is it better to ask a question like this in an issue in the Cobra github site?

The application I am trying to write will be used extremely often, and I want to minimize the required syntax.

I want to set up a command line like the following:

    <applicationname> <parameter> <subcommand> <parameters>

The parameter right after the application name will always be present. I don't want it to be a flag. After that parameter value will be a subcommand, followed by additional parameters, also not flags. There are some situations where I want to allow for flags, but that will be uncommon.

It's not clear to me how to cleanly set up this organization.  Is it simply not practical to do with Cobra?  Should I just do ad hoc parameter processing?

burak serdar

unread,
Feb 25, 2024, 1:52:10 PMFeb 25
to David Karr, golang-nuts
You can do rootCmd.SetArgs(os.Args[2:]), and process the first
parameter yourself.
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/14b9efb1-7fbb-45a6-8e0e-56f25be310a3n%40googlegroups.com.

David Karr

unread,
Feb 25, 2024, 3:49:48 PMFeb 25
to golang-nuts
But where would that be done?  I'm not certain of the exact role of the "rootCmd.Execute()" function, or the optional "Run" function in the Command object. Neither of those appear to be executed, when I just run "<app> <param> <subcommand"". I put a print statement in the "Run" function in the subcommand, and that gets printed, but nothing else.

burak serdar

unread,
Feb 25, 2024, 4:04:10 PMFeb 25
to David Karr, golang-nuts
Somewhere in your main, you should be calling rootCmd.Execute(). Instead:

func main() {
// first, make sure there are at least 2 args. Then, process the
1st parameter
// Then
rootCmd.SetArgs(os.Args[2:])
rootCmd.Execute()
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9d8fac62-f70a-488d-8bf9-7800b5d44d34n%40googlegroups.com.

David Karr

unread,
Feb 25, 2024, 4:41:47 PMFeb 25
to golang-nuts
Ok, that worked. I had tried that before, but I had done it wrong.
Reply all
Reply to author
Forward
0 new messages