Skip to content

How can I replace dashes/hyphens in flag names with underscores? #1054

Discussion options

You must be logged in to vote

Answered by @megapctr in #1044 (comment):

I found a solution, this issue is just for folks who may also be struggling with this. Feel free to close it, unless you think it's worth mentioning in the readme.

I wanted to keep my CLI flags in kebab-case and my config keys in snake_case. I've been searching for something like EnvKeyReplacer but for flags. Turns out pflag.FlagSet has a function for normalizing flag names.

This solved my issue:

// bind cmd flags to viper, replacing dashes with underscores
f := cmd.Flags()
normalizeFunc := f.GetNormalizeFunc()
f.SetNormalizeFunc(func(fs *pflag.FlagSet, name string) pflag.NormalizedName {
    result := normalizeFunc(fs, name)
    name = strings.R…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by sagikazarmark
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants