github.com/richardwilkes/toolbox@v1.121.0/xio/term/getch.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  //go:build !windows
    11  
    12  package term
    13  
    14  import (
    15  	"github.com/pkg/term"
    16  )
    17  
    18  // Read a byte from the terminal.
    19  func Read() (ch byte, ok bool) {
    20  	t, err := term.Open("/dev/tty")
    21  	if err != nil {
    22  		return 0, false
    23  	}
    24  	err = term.RawMode(t)
    25  	if err != nil {
    26  		return 0, false
    27  	}
    28  	bytes := make([]byte, 1)
    29  	numRead, err := t.Read(bytes)
    30  	if altErr := t.Restore(); altErr != nil && err == nil {
    31  		err = altErr
    32  	}
    33  	if altErr := t.Close(); altErr != nil && err == nil {
    34  		err = altErr
    35  	}
    36  	if err != nil || numRead == 0 {
    37  		return 0, false
    38  	}
    39  	return bytes[0], true
    40  }