Reordering error output in flags package so Usage is printed before the error?

48 views
Skip to first unread message

Thomas Nyberg

unread,
Dec 8, 2019, 6:00:44 AM12/8/19
to golan...@googlegroups.com
Hello,

Given the following file `flag_example.go`:

package main

import "flag"

func main
() {
    flagName
:= flag.String("flagName", "flagValue", "Help message.")
    flag
.Parse()
    _
= flagName
}

If I execute it with a bad flag passed I see the following:

$ ./flag_example -flagName
flag needs an argument
: -flagName
Usage of ./flag_example:
 
-flagName string
       
Help message. (default "flagValue")

What I would like to see is something like the following:

$ ./flag_example -flagName
Usage of ./flag_example:
 
-flagName string
       
Help message. (default "flagValue")

flag needs an argument: -flagName

In other words, I would like to move the error to the end. Is there an easy way to achieve this? I know about changing Usage, but that doesn't seem to affect this specific issue. Thanks for any help!

Cheers,
Thomas

Thomas Nyberg

unread,
Dec 8, 2019, 7:06:42 AM12/8/19
to golang-nuts
Hello,

I looked at the source and noticed that if I move the following line up two lines I guess basically what I'm looking for:


But this is changing an unexported function. Is there a way to do something like this without messing with the source of standard library?

Cheers,
Thomas

andrey mirtchovski

unread,
Dec 8, 2019, 1:06:26 PM12/8/19
to Thomas Nyberg, golang-nuts
You'll need to create a FlagSet instead and pass ContinueOnError as
the error handling. If .Parse() returns an error call
.PrintDefaults(), then print the error.
> --
> 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/CADDBb4JFEEhQcHVF2csObgCdEgQaGGQYJntYoiWYYOjko8tEzw%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages