os Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/os/ Tue, 05 Jan 2021 15:20:51 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 os Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/os/ 32 32 159787465 Return exit status code in Go (Golang) https://vikasboss.github.io/return-exit-status-code-go/ https://vikasboss.github.io/return-exit-status-code-go/#respond Mon, 13 Apr 2020 11:33:35 +0000 https://vikasboss.github.io/?p=1985 Overview ‘os’ package of golang provides an Exit function that can be used to exit the current program with a status code. Status code zero means success Non-zero status code means an...

The post Return exit status code in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘os’ package of golang provides an Exit function that can be used to exit the current program with a status code.

  • Status code zero means success
  • Non-zero status code means an error.

Once this function is called the program exits immediately. Even the deferred functions are not called.

Also to note that status code should be in the range [0, 125]

func Exit(code int)

Let’s see a working code

Code

package main

import (
    "fmt"
    "os"
)

func main() {
    success := true
    if success {
        fmt.Println("Success")
        os.Exit(0)
    } else {
        fmt.Println("Failure")
        os.Exit(1)
    }
}

Output

Try setting success to false to see a different output

Success
$ echo $?
0

The post Return exit status code in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/return-exit-status-code-go/feed/ 0 1985
Get Hostname in Go (Golang) https://vikasboss.github.io/get-hostname-golang/ https://vikasboss.github.io/get-hostname-golang/#respond Mon, 13 Apr 2020 08:16:20 +0000 https://vikasboss.github.io/?p=1980 Overview ‘os’ package of golang provides a Hostname function that can be used to get the hostname that is reported by the kernelBelow is the signature of this method. It returns an...

The post Get Hostname in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘os’ package of golang provides a Hostname function that can be used to get the hostname that is reported by the kernel
Below is the signature of this method. It returns an error if not able to successfully get the hostname

func Hostname() (name string, err error)

Let’s see a working code

Code

package main

import (
	"fmt"
	"os"
)

func main() {
	hostname, err := os.Hostname()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Printf("Hostname: %s", hostname)
}

Output:

Hostname: 

The post Get Hostname in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/get-hostname-golang/feed/ 0 1980