Home Backend Development Golang How to use keyboard input and output in Golang

How to use keyboard input and output in Golang

Apr 11, 2023 am 09:14 AM

Golang is an efficient, modern language that is very convenient and practical when developing applications. This article will introduce how to use keyboard input and output in Golang.

1. Use the fmt package to output
The fmt package is a very commonly used package in the Golang standard library and provides many useful functions. This includes outputting content to the console. Using the fmt package to output is very simple, just call the fmt.Println() function:

package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}
Copy after login

Run this code, we can see the output "Hello, world!" on the console.

2. Use bufio package for input
In addition to output, input is also a function we often need to use. Golang provides the bufio package, which can conveniently read user input. The following is a simple example of reading user input and output:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println("You entered: ", text)
}
Copy after login

In this code, we first imported the bufio package and os package, and created a reader variable in the main function for reading User input. Call the fmt.Print() function to output prompt information, wait for user input, and then use the reader.ReadString() function to read the user input. Finally, use the fmt.Println() function to output what the user entered.

3. Use third-party libraries to provide a better input/output experience

Although the above method is convenient, it only implements the most basic input and output functions. If a better user experience is needed, we can consider using third-party libraries. The following are two libraries worth recommending:

  1. termui
    termui is a terminal-based user interface library that provides many useful UI components that can make our Golang applications look more major. The following is a simple example implemented using termui:
package main

import (
    "github.com/gizak/termui/v3"
    "github.com/gizak/termui/v3/widgets"
)

func main() {
    err := termui.Init()
    if err != nil {
        panic(err)
    }
    defer termui.Close()

    p := widgets.NewParagraph()
    p.Text = "Enter text here:"
    p.SetRect(0, 0, 25, 3)

    tb := widgets.NewTextEdit()
    tb.SetRect(0, 3, 25, 5)

    termui.Render(p, tb)

    for e := range termui.PollEvents() {
        if e.Type == termui.KeyboardEvent {
            if e.ID == "q" {
                return
            }
            if e.ID == "<Enter>" {
                p.Text = "You entered " + tb.Text
                tb.SetText("")
            }
            termui.Render(p, tb)
        }
    }
}
Copy after login

In this example, we use termui's widgets.NewParagraph() and widgets.NewTextEdit() functions to create a paragraph and text edit box . The Render() function is used to render these components in the terminal. We also used the PollEvents() function to handle user input. When the user enters the Enter key, we use p.Text to update the prompt information and tb.Text to obtain the user input.

  1. gocui
    gocui is another library for creating terminal GUIs. It provides some common GUI components, such as windows, input boxes, buttons, etc. The following is a simple example implemented using gocui:
package main

import (
    "github.com/jroimartin/gocui"
)

func main() {
    g, err := gocui.NewGui(gocui.OutputNormal)
    if err != nil {
        panic(err)
    }
    defer g.Close()

    g.SetManagerFunc(func(g *gocui.Gui) error {
        if v, err := g.SetView("prompt", 0, 0, 25, 3); err != nil {
            if err != gocui.ErrUnknownView {
                return err
            }
            v.Title = "Enter text"
            v.Editable = true
            v.Wrap = true
            if _, err := g.Cursor(true); err != nil {
                return err
            }
            if err := g.SetKeybinding("prompt", gocui.KeyEnter, gocui.ModNone, enterHandler); err != nil {
                return err
            }
            if err := v.SetCursor(0, 0); err != nil {
                return err
            }
        }
        return nil
    })

    if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
        panic(err)
    }
}

func enterHandler(g *gocui.Gui, v *gocui.View) error {
    if _, err := g.View("prompt"); err != nil {
        return err
    }
    text := v.Buffer()
    if err := g.DeleteView("prompt"); err != nil {
        return err
    }
    if _, err := g.SetCurrentView(""); err != nil {
        return err
    }
    g.Update(func(g *gocui.Gui) error {
        return g.Close()
    })
    println("You entered: ", text)
    return nil
}
Copy after login

In this example, we use gocui's gocui.NewGui() function to create a GUI object, and use the g.SetManagerFunc() function Configure the GUI interface as an edit box. We also used the g.SetKeybinding() function to set the shortcut keys and implemented the enterHandler() function to handle user input.

Summary:
It is very convenient to use keyboard input and output in Golang. We can use the fmt and bufio packages in the Golang standard library to complete basic input and output operations. If we need a better user experience, we can also use the third-party libraries termui and gocui to create a terminal GUI.

The above is the detailed content of How to use keyboard input and output in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

See all articles