Golang : How to check if your program is running in a terminal
Problem:
Your command line application accepts inputs from a terminal only or you just want to test if the application is really running under a terminal. How to check if the application is really running under a terminal?
Solution:
Use the github.com/mattn/go-isatty package to determine if your application running under Terminal, Windows Cygwin/MSYS2.
For example, running this code ( from github.com/mattn/go-isatty ) under a terminal
package main
import (
"fmt"
"github.com/mattn/go-isatty"
"os"
)
func main() {
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println("Is Terminal")
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
fmt.Println("Is Cygwin/MSYS2 Terminal")
} else {
fmt.Println("Is Not Terminal")
}
}
will give:
Is Terminal
and if you execute the code under Gogland IDE, you will get Is Not Terminal
:
GOROOT=/usr/local/go
GOPATH=/Users/admin/go
/usr/local/go/bin/go build -i -o /private/var/folders/mt/p1knsj5x45901p6t3q0kxpq40000gn/T/Buildmaingoandrungo
/Users/admin/GoglandProjects/ReallyTerminal/main.go
/private/var/folders/mt/p1knsj5x45901p6t3q0kxpq40000gn/T/Buildmaingoandrungo
Is Not Terminal
Process finished with exit code 0
Hope this helps!
See also : Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.4k Golang : Read file with ioutil
+7.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+6.7k Golang : Calculate pivot points for a cross
+18.5k Golang : Implement getters and setters
+10.2k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+9.3k Golang : Extract or copy items from map based on value
+17.1k Golang : When to use init() function?
+11.3k Android Studio : Create custom icons for your application example
+5.2k Golang : Generate Interleaved 2 inch by 5 inch barcode
+23.4k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+22.5k Golang : Set and Get HTTP request headers example
+5.3k Golang : If else example and common mistake