Practical input handling involves managing different types of input streams, processing complex data, and implementing robust error handling strategies.
1. CSV-like Data Processing
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func processCSVInput() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Enter CSV-like data (Name,Age,City):")
for scanner.Scan() {
fields := strings.Split(scanner.Text(), ",")
if len(fields) == 3 {
name, age, city := fields[0], fields[1], fields[2]
fmt.Printf("Processed: Name=%s, Age=%s, City=%s\n", name, age, city)
}
}
}
Strategy |
Description |
Use Case |
Validation |
Check input format |
Data integrity |
Transformation |
Convert input types |
Data processing |
Error Recovery |
Handle invalid inputs |
Robust applications |
graph TD
A[Receive Input] --> B{Validate Input}
B --> |Valid| C[Process Data]
B --> |Invalid| D[Error Handling]
C --> E[Transform/Store]
D --> F[Log Error]
F --> G[Request Retry]
Timeout Handling
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func inputWithTimeout() {
inputChan := make(chan string)
go func() {
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
inputChan <- scanner.Text()
}
}()
select {
case input := <-inputChan:
fmt.Println("Received input:", input)
case <-time.After(5 * time.Second):
fmt.Println("Input timeout")
}
}
func validateInput(input string) bool {
// Custom validation logic
return len(input) > 0 && len(input) <= 100
}
func processInput() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input := scanner.Text()
if validateInput(input) {
// Process valid input
fmt.Println("Valid input:", input)
} else {
fmt.Println("Invalid input")
}
}
}
LabEx Recommended Practices
- Implement comprehensive input validation
- Use buffered scanning for efficient memory management
- Design flexible error handling mechanisms
- Minimize memory allocation
- Use efficient scanning techniques
- Implement early validation to reduce processing overhead
Error Handling Strategies
- Validate input format
- Provide clear error messages
- Offer input retry mechanisms
- Log invalid input attempts