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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

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,...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

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...

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. �...

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

See all articles