// defaultFeatureGates consists of all known specific feature keys. // To add a new feature, define a key for it above and add it here. var defaultFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{ // owner: @colin404 // Deprecated: v1.31 // // An example feature gate. MyNewFeature: {Default: false, PreRelease: featuregate.Alpha}, }
funcmain() { // Create a new FlagSet for managing command-line flags fs := pflag.NewFlagSet("feature", pflag.ExitOnError)
// Set the usage function to provide a custom help message fs.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) fs.PrintDefaults() }
// Define a boolean flag for displaying help help := fs.BoolP("help", "h", false, "Show this help message.")
// Add the feature gates to the flag set feature.DefaultMutableFeatureGate.AddFlag(fs)
// Parse the command-line flags fs.Parse(os.Args[1:])
// Display help message if the help flag is set if *help { fs.Usage() return }
// Check if the MyNewFeature feature gate is enabled if feature.DefaultFeatureGate.Enabled(feature.MyNewFeature) { // Logic when the new feature is enabled fmt.Println("Feature Gates: MyNewFeature is opened") } else { // Logic when the new feature is disabled fmt.Println("Feature Gates: MyNewFeature is closed") } }
应用启动时给特性门控初始化
1 2 3 4 5 6 7 8 9 10 11
$ go run main.go -h Usage of /tmp/go-build224395384/b001/exe/main: --feature-gates mapStringBool A set of key=value pairs that describe feature gates for alpha/experimental features. Options are: AllAlpha=true|false (ALPHA - default=false) AllBeta=true|false (BETA - default=false) MyNewFeature=true|false (ALPHA - default=false) -h, --help Show this help message. $ go run main.go --feature-gates=MyNewFeature=false Feature Gates: MyNewFeature is closed $ go run main.go --feature-gates=MyNewFeature=true Feature Gates: MyNewFeature is opened