Golang os.Expand() and ExpandEnv() functions example
package os
Golang os.Expand() and ExpandEnv() functions usage example
package main
import (
"fmt"
"os"
)
func testGetenv(s string) string {
switch s {
case "*":
return "all the args"
case "#":
return "NARGS"
case "$":
return "PID"
case "1":
return "ARGUMENT1"
case "HOME":
return "/usr/gopher"
case "H":
return "(Value of H)"
case "home_1":
return "/usr/foo"
case "_":
return "underscore"
}
return ""
}
func main() {
str := os.Expand("$1", testGetenv)
fmt.Println(str)
str = os.Expand("$HOME", testGetenv)
fmt.Println(str)
// ----------------------------
str = os.Expand("HOME", os.Getenv) // without $ is wrong way to use os.Expand function
fmt.Println(str)
str = os.Expand("$HOME", os.Getenv) // extract from environment
fmt.Println(str)
str = os.ExpandEnv("$HOME") // another way to extract from environment
fmt.Println(str)
}
Sample output :
ARGUMENT1
/usr/gopher
HOME
/root
/root
References :
Advertisement
Something interesting
Tutorials
+14.2k Golang : syscall.Socket example
+19.8k Golang : Append content to a file
+15.6k Golang : How to convert(cast) IP address to string?
+9k Golang : Capture text return from exec function example
+7.5k Golang : Process json data with Jason package
+19.2k Golang : Delete item from slice based on index/key position
+15.4k Golang : Find location by IP address and display with Google Map
+17.2k Golang : When to use init() function?
+9.1k Golang : Handle sub domain with Gin
+6.1k Golang : Grab news article text and use NLP to get each paragraph's sentences
+48.5k Golang : Upload file from web browser to server
+11.1k Golang : Roll the dice example