Runtime detection lets Go applications discover host and execution-environment characteristics while running, avoiding assumptions that break across operating systems, deployment environments, or dynamically scheduled instances. section 12.4.1
Use standard and supporting system interfaces to inspect the running environment:
- Use os.Hostname for the kernel hostname and os.Getpid for the application process ID. section 12.4.1
- Use os.PathSeparator and os.PathListSeparator instead of hardcoded separators for portable paths. section 12.4.1
- Use os.Getwd to find the current working directory, and combine os information with net or external commands for additional details. section 12.4.1
Listing 12.10 Looking up the host’s IP addresses via the hostname
func main() {
name, err := os.Hostname() #1
if err != nil { #1
fmt.Println(err) #1
return #1
} #1
addrs, err := net.LookupHost(name) #2
if err != nil { #2
fmt.Println(err) #2
return #2
} #2
for _, a := range addrs { #3
fmt.Println(a) #3
}
Looks up the hostname with os.Hostname, resolves it through net.LookupHost, handles errors, and prints the resulting addresses. section 12.4.1
Checking a runtime dependency
A dependency check can call exec.LookPath, return a descriptive error when an executable is absent from PATH, and stop startup with log.Fatalln. section 12.4.1
