Skip to main content

Command Palette

Search for a command to run...

GoLang Series Part 4: User Input from Keyboard

Updated
2 min read
GoLang Series Part 4: User Input from Keyboard
N

👋 Welcome to my Hashnode profile! I'm a passionate technologist with expertise in AWS, DevOps, Kubernetes, Terraform, Datree, and various cloud technologies. Here's a glimpse into what I bring to the table: 🌟 Cloud Aficionado: I thrive in the world of cloud technologies, particularly AWS. From architecting scalable infrastructure to optimizing cost efficiency, I love diving deep into the AWS ecosystem and crafting robust solutions. 🚀 DevOps Champion: As a DevOps enthusiast, I embrace the culture of collaboration and continuous improvement. I specialize in streamlining development workflows, implementing CI/CD pipelines, and automating infrastructure deployment using modern tools like Kubernetes. ⛵ Kubernetes Navigator: Navigating the seas of containerization is my forte. With a solid grasp on Kubernetes, I orchestrate containerized applications, manage deployments, and ensure seamless scalability while maximizing resource utilization. 🏗️ Terraform Magician: Building infrastructure as code is where I excel. With Terraform, I conjure up infrastructure blueprints, define infrastructure-as-code, and provision resources across multiple cloud platforms, ensuring consistent and reproducible deployments. 🌳 Datree Guardian: In my quest for secure and compliant code, I leverage Datree to enforce best practices and prevent misconfigurations. I'm passionate about maintaining code quality, security, and reliability in every project I undertake. 🌐 Cloud Explorer: The ever-evolving cloud landscape fascinates me, and I'm constantly exploring new technologies and trends. From serverless architectures to big data analytics, I'm eager to stay ahead of the curve and help you harness the full potential of the cloud. Whether you need assistance in designing scalable architectures, optimizing your infrastructure, or enhancing your DevOps practices, I'm here to collaborate and share my knowledge. Let's embark on a journey together, where we leverage cutting-edge technologies to build robust and efficient solutions in the cloud! 🚀💻

Introduction

In this part of the Go series, we will learn how to handle user input from the keyboard. Handling user input is a fundamental aspect of creating interactive applications. Go provides straightforward ways to read input from the standard input (keyboard) using packages like bufio and os.

Example

Let's look at an example where we will prompt the user to enter their name, and then we will greet them. Additionally, we will demonstrate how to handle potential errors when opening a file.

package main

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

func main() {
    initMessage := "This is an example for UserInput from Keyboard"
    fmt.Println(initMessage)

    reader := bufio.NewReader(os.Stdin)
    fmt.Println("What is Your Name?")

    input, _ := reader.ReadString('\n')
    fmt.Println("Hi,", input)
    fmt.Printf("The entered value is of Type: %T\n", input)

    file, err := os.Open("newfile.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("The file exists:", file)
}

How to Run

  1. Save the code in a file named main.go.

  2. Open your terminal or command prompt.

  3. Navigate to the directory where main.go is saved.

  4. Run the command: go run main.go.

  5. Follow the prompt to enter your name.

Output

When you run the program, you will see the following output:

This is an example for UserInput from Keyboard
What is Your Name?
<your_name>
Hi, <your_name>
The entered value is of Type: string

If the file newfile.txt exists in the same directory, it will print:

The file exists: &{0xc000010260}

If the file does not exist, it will print an error message and terminate the program.

Explanation

  • Initialization: We print an initial message to the console.

  • Buffered Reader: We create a bufio.Reader to read input from the standard input (os.Stdin).

  • Reading Input: We prompt the user for their name and read the input using reader.ReadString('\n'). This function reads until the newline character is encountered.

  • Greeting the User: We print a greeting message including the user's input.

  • Type Printing: We print the type of the user input, which is a string.

  • File Handling: We attempt to open a file named newfile.txt. If the file does not exist, os.Open returns an error which is handled by log.Fatal. This function logs the error and stops the execution of the program.

Conclusion

In this part, we covered how to read user input from the keyboard in Go and handle basic file operations. These skills are essential for developing interactive applications. In the next part, we will dive into the "comma ok" or "error ok" syntax in Go, which is a common pattern for error handling and type assertions.

Next: Comma OK or Error OK Syntax in Go

More from this blog

NavyaDevops

78 posts

DevOps Engineer with advanced skills in cloud technologies. Proven track record in optimizing development and deployment processes. Dedicated to innovation and scalability in software development.