How to get the hostname of the node in Go?

Posted on In QA

In Go lang, how to get the hostname of the node?

In Go, you can use the os.Hostname() function to get the hostname of the node.

func Hostname() (name string, err error)

Hostname returns the host name reported by the kernel.

One example is as follows. The main.go source code:

package main

import (
	"fmt"
	"os"
)

func main() {
	name, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	fmt.Println("hostname:", name)
}

Run it:

$ go run main.go
hostname: host001

Leave a Reply

Your email address will not be published. Required fields are marked *