publish environment variables example

This commit is contained in:
Mark McGranaghan 2012-10-10 08:46:34 -07:00
parent d72ff01446
commit 202a4a45b0
4 changed files with 38 additions and 18 deletions

View File

@ -63,7 +63,7 @@ Sorting by Functions
Line Filters
# Command-Line Arguments
# Command-Line Flags
# Environment Variables
Environment Variables
# Spawning Processes
# Execing Processes
# Signals

View File

@ -1,24 +1,31 @@
// [Environment variables](http://en.wikipedia.org/wiki/Environment_variable)
// are a universal mechanism for [conveying configuration
// information to Unix programs](http://www.12factor.net/config).
// Let's look at how to set, get, and list environment variables.
package main
// Use the `os` package to list, set, and get environment
// variables.
import "os"
import "strings"
import "fmt"
func main() {
// `os.Environ` returns a slice of strings in the form
// `KEY=value`. You can `strings.Split` them to get
// the key and value.
// To set a key/value pair, use `os.Setenv`. To get a
// value for a key, use `os.Getenv`. This will return
// an empty string if the key isn't present in the
// environment.
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
// Use `os.Environ` to list all key/value pairs in the
// environment. This returns a slice of strings in the
// form `KEY=value`. You can `strings.Split` them to
// get the key and value. Here we print all the keys.
fmt.Println()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[0])
}
fmt.Println()
// `Setenv` sets a given key, value pair.
// `Getenv` returns the value at key, or an empty
// string if the key isn't present.
os.Setenv("FOO", "bar")
fmt.Println(os.Getenv("FOO"))
}

View File

@ -1,6 +1,19 @@
# Running the program shows that we pick up the value
# value for `FOO` that we set in the program.
$ go run environment-variables.go
HOME
FOO: 1
BAR:
# The list of keys in the environment will depend on your
# particular machine.
TERM_PROGRAM
PATH
PWD
SHELL
...
# If we set `BAR` in the environemnt first, the running
# program picks that value up.
$ BAR=2 go run environment-variables.go
FOO: 1
BAR: 2
...
bar

View File

@ -21,7 +21,7 @@ func readLines(path string) []string {
return strings.Split(string(srcBytes), "\n")
}
var todoPat = regexp.MustCompile("\\/\\/ todo: ")
var commentPat = regexp.MustCompile("\\s*\\/\\/")
func main() {
sourcePaths, err := filepath.Glob("./examples/*/*")
@ -31,7 +31,7 @@ func main() {
foundLongLine := false
lines := readLines(sourcePath)
for i, line := range lines {
if !foundLongLine && !todoPat.MatchString(line) && (len(line) > 58) {
if !foundLongLine && !commentPat.MatchString(line) && (len(line) > 58) {
fmt.Printf("measure: %s:%d\n", sourcePath, i+1)
foundLongLine = true
foundLongFile = true