github.com/openimsdk/tools@v0.0.49/env/env.go (about)

     1  // Copyright © 2024 OpenIM open source community. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package env
    16  
    17  import (
    18  	"os"
    19  	"strconv"
    20  
    21  	"github.com/openimsdk/tools/errs"
    22  )
    23  
    24  // GetString returns the env variable for the given key
    25  // and falls back to the given defaultValue if not set.
    26  func GetString(key, defaultValue string) string {
    27  	v, ok := os.LookupEnv(key)
    28  	if ok {
    29  		return v
    30  	}
    31  	return defaultValue
    32  }
    33  
    34  // GetInt returns the env variable (parsed as integer) for
    35  // the given key and falls back to the given defaultValue if not set.
    36  func GetInt(key string, defaultValue int) (int, error) {
    37  	v, ok := os.LookupEnv(key)
    38  	if ok {
    39  		value, err := strconv.Atoi(v)
    40  		if err != nil {
    41  			return defaultValue, errs.WrapMsg(err, "Atoi failed", "value", v)
    42  		}
    43  		return value, nil
    44  	}
    45  	return defaultValue, nil
    46  }
    47  
    48  // GetFloat64 returns the env variable (parsed as float64) for
    49  // the given key and falls back to the given defaultValue if not set.
    50  func GetFloat64(key string, defaultValue float64) (float64, error) {
    51  	v, ok := os.LookupEnv(key)
    52  	if ok {
    53  		value, err := strconv.ParseFloat(v, 64)
    54  		if err != nil {
    55  			return defaultValue, errs.WrapMsg(err, "ParseFloat failed", "value", v)
    56  		}
    57  		return value, nil
    58  	}
    59  	return defaultValue, nil
    60  }
    61  
    62  // GetBool returns the env variable (parsed as bool) for
    63  // the given key and falls back to the given defaultValue if not set.
    64  func GetBool(key string, defaultValue bool) (bool, error) {
    65  	v, ok := os.LookupEnv(key)
    66  	if ok {
    67  		value, err := strconv.ParseBool(v)
    68  		if err != nil {
    69  			return defaultValue, errs.WrapMsg(err, "ParseBool failed", "value", v)
    70  		}
    71  		return value, nil
    72  	}
    73  	return defaultValue, nil
    74  }