Created
August 30, 2019 10:24
-
-
Save bindiego/21e46ca6505c81a71edab2d79077d0b2 to your computer and use it in GitHub Desktop.
Golang get fully qualified domain name / hostname
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"os/exec" | |
"strings" | |
"bytes" | |
//"time" | |
) | |
func get_hostname(hostname_override string) (string, error) { | |
hostname := hostname_override | |
if len(hostname) == 0 { | |
node_name, err := os.Hostname() | |
if err != nil { | |
return "", fmt.Errorf("couldn't determine hostname: %v", err) | |
} | |
hostname = node_name | |
} | |
hostname = strings.TrimSpace(hostname) | |
if len(hostname) == 0 { | |
return "", fmt.Errorf("empty hostname is invalid") | |
} | |
return strings.ToLower(hostname), nil | |
} | |
func get_hostname_fqdn() (string, error) { | |
cmd := exec.Command("/bin/hostname", "-f") | |
var out bytes.Buffer | |
cmd.Stdout = &out | |
err := cmd.Run() | |
if err != nil { | |
return "", fmt.Errorf("Error when get_hostname_fqdn: %v", err) | |
} | |
fqdn := out.String() | |
fqdn = fqdn[:len(fqdn)-1] // removing EOL | |
return fqdn, nil | |
} | |
func main() { | |
hostname, err := get_hostname("bindigo.internal") | |
// hostname, err := get_hostname("") | |
if err != nil { | |
return | |
} | |
fmt.Println("hostname: " + hostname) | |
hn_fqdn, err := get_hostname_fqdn() | |
fmt.Println("hostname_fqdn: " + hn_fqdn) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -ex | |
go build binwu.go | |
./binwu |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Appreciated your information 👍 love it