Go by Example: Line Filters

A line filter is a common type of program that reads input from stdin, processes it, and then outputs the result to stdout. Here’s an example in Go that implements a line filter that converts all input to uppercase:

package main

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

func main() {
	// Create a new scanner to read from stdin
	scanner := bufio.NewScanner(os.Stdin)

	// Read each line of input from stdin
	for scanner.Scan() {
		// Convert the line to uppercase
		line := strings.ToUpper(scanner.Text())

		// Write the line to stdout
		fmt.Println(line)
	}

	// Check for any errors during scanning
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "Error reading from stdin:", err)
	}
}

In this example, we use the bufio.NewScanner function to create a new bufio.Scanner that reads from os.Stdin. The scanner.Scan method is then used in a loop to read each line of input from os.Stdin.

For each line of input, we use the strings.ToUpper function to convert the line to uppercase and then write it to os.Stdout using fmt.Println.

Finally, we check for any errors that may have occurred during the scanning process using the scanner.Err method and print an error message to os.Stderr if there was an error.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *