Saturday, April 27, 2024
HomeGolangSetting variables in Go (Golang)

Setting variables in Go (Golang)



Setting variables are sometimes used as a method to retailer the app configuration values. As an alternative of holding delicate knowledge like passwords in a code repository, we are able to simply set them as setting variables that this system then reads whereas operating. In Golang’s os bundle, there are some capabilities that make it simple to set or unset setting variables, get or record setting variables, and clear setting variables.

Have a look at the instance to match how these capabilities work:

bundle predominant

import (
    "fmt"
    "log"
    "os"
    "strings"
)

const userKey = "GOSAMPLES_USER"

func predominant() {
    // set setting variable
    err := os.Setenv(userKey, "admin")
    if err != nil {
        log.Deadly(err)
    }

    // get setting variable
    fmt.Printf("os.Getenv(): %s=%sn", userKey, os.Getenv(userKey))

    // iterate over all setting variables and examine if our variable is ready
    for _, envStr := vary os.Environ() {
        if strings.HasPrefix(envStr, userKey) {
            fmt.Printf("os.Environ(): %s setting variable is ready: %sn", userKey, envStr)
        }
    }

    // lookup setting variable
    val, isSet := os.LookupEnv(userKey)
    fmt.Printf("os.LookupEnv(): %s variable is ready: %t, worth: %sn", userKey, isSet, val)

    // unset setting variable
    if err := os.Unsetenv(userKey); err != nil {
        log.Deadly(err)
    }

    // lookup setting variable once more - now it shouldn't be set
    val, isSet = os.LookupEnv(userKey)
    fmt.Printf("os.Unsetenv(); %s variable is ready: %t, worth: %sn", userKey, isSet, val)

    // clear setting variables
    os.Clearenv()
    fmt.Printf("os.Clearenv(): variety of setting variables: %dn", len(os.Environ()))
}

Output:

os.Getenv(): GOSAMPLES_USER=admin
os.Environ(): GOSAMPLES_USER setting variable is ready: GOSAMPLES_USER=admin
os.LookupEnv(): GOSAMPLES_USER variable is ready: true, worth: admin
os.Unsetenv(); GOSAMPLES_USER variable is ready: false, worth: 
os.Clearenv(): variety of setting variables: 0
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments