github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/regFlags.go (about)

     1  // Copyright 2017-present Kirill Danshin and Gramework contributors
     2  // Copyright 2019-present Highload LTD (UK CN: 11893420)
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  
    11  package gramework
    12  
    13  import (
    14  	"flag"
    15  )
    16  
    17  var flagsDisabled = false
    18  
    19  var flagsToRegister = []Flag{
    20  	{
    21  		Name:        "bind",
    22  		Description: "address to listen",
    23  		Default:     ":80",
    24  	},
    25  }
    26  
    27  // AddFlag adds a Flag to flag queue that will be
    28  // parsed if flags wasn't parsed yet
    29  func (app *App) AddFlag(f Flag) {
    30  	if app.flagsQueue == nil {
    31  		app.flagsQueue = make([]Flag, 0)
    32  	}
    33  	app.flagsQueue = append(app.flagsQueue, f)
    34  }
    35  
    36  // RegFlags registers current flag queue in flag parser
    37  func (app *App) RegFlags() {
    38  	if app.Flags.values == nil {
    39  		app.Flags.values = make(map[string]Flag)
    40  	}
    41  	app.flagsRegistered = true
    42  	for _, v := range app.flagsQueue {
    43  		app.Flags.values[v.Name] = Flag{
    44  			Name:        v.Name,
    45  			Description: v.Description,
    46  			Default:     v.Default,
    47  			Value:       flag.String(v.Name, v.Default, v.Description),
    48  		}
    49  	}
    50  }
    51  
    52  // GetStringFlag return command line app flag value by name and false if not exists
    53  func (app *App) GetStringFlag(name string) (string, bool) {
    54  	if !flag.Parsed() && !flagsDisabled {
    55  		flag.Parse()
    56  	}
    57  	if app.Flags.values != nil {
    58  		if bindFlag, ok := app.Flags.values[name]; ok {
    59  			return *bindFlag.Value, ok
    60  		}
    61  	}
    62  
    63  	return "", false
    64  }
    65  
    66  // DisableFlags globally disables default flags.
    67  // Useful when using non-default flag libraries like pflag.
    68  func DisableFlags() {
    69  	flagsDisabled = true
    70  	flagsToRegister = []Flag{}
    71  }