github.com/zhongdalu/gf@v1.0.0/g/internal/cmdenv/cmdenv.go (about)

     1  // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  // Package cmdenv provides access to certain variable for both command options and environment.
     8  package cmdenv
     9  
    10  import (
    11  	"github.com/zhongdalu/gf/g/container/gvar"
    12  	"os"
    13  	"regexp"
    14  	"strings"
    15  )
    16  
    17  var (
    18  	// Console options.
    19  	cmdOptions = make(map[string]string)
    20  )
    21  
    22  func init() {
    23  	doInit()
    24  }
    25  
    26  // doInit does the initialization for this package.
    27  func doInit() {
    28  	reg := regexp.MustCompile(`\-\-{0,1}(.+?)=(.+)`)
    29  	for i := 0; i < len(os.Args); i++ {
    30  		result := reg.FindStringSubmatch(os.Args[i])
    31  		if len(result) > 1 {
    32  			cmdOptions[result[1]] = result[2]
    33  		}
    34  	}
    35  }
    36  
    37  // Get returns the command line argument of the specified <key>.
    38  // If the argument does not exist, then it returns the environment variable with specified <key>.
    39  // It returns the default value <def> if none of them exists.
    40  //
    41  // Fetching Rules:
    42  // 1. Command line arguments are in lowercase format, eg: gf.<package name>.<variable name>;
    43  // 2. Environment arguments are in uppercase format, eg: GF_<package name>_<variable name>;
    44  func Get(key string, def ...interface{}) *gvar.Var {
    45  	value := interface{}(nil)
    46  	if len(def) > 0 {
    47  		value = def[0]
    48  	}
    49  	if v, ok := cmdOptions[key]; ok {
    50  		value = v
    51  	} else {
    52  		key = strings.ToUpper(strings.Replace(key, ".", "_", -1))
    53  		if v := os.Getenv(key); v != "" {
    54  			value = v
    55  		}
    56  	}
    57  	return gvar.New(value, true)
    58  }