Practical Scanning Examples
Real-World Scanning Scenarios
1. Log File Analysis
func analyzeLogFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
errorCount := 0
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "ERROR") {
errorCount++
fmt.Println("Error detected:", line)
}
}
fmt.Printf("Total errors found: %d\n", errorCount)
return scanner.Err()
}
2. CSV Data Processing
func processCSVData(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanFunc(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
for i := 0; i < len(data); i++ {
if data[i] == ',' {
return i + 1, data[:i], nil
}
}
return 0, nil, nil
}))
for scanner.Scan() {
field := scanner.Text()
fmt.Println("CSV Field:", field)
}
return scanner.Err()
}
Scanning Use Cases
Scenario |
Use Case |
Scanning Technique |
Log Analysis |
Filtering errors |
Line scanning |
Data Processing |
CSV parsing |
Delimiter scanning |
Configuration |
Reading config files |
Line scanning |
Network Protocols |
Parsing streams |
Custom delimiter |
Advanced Scanning Techniques
Custom Delimiter Scanning
func customDelimiterScanning() {
input := "apple:banana:cherry:date"
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
for i := 0; i < len(data); i++ {
if data[i] == ':' {
return i + 1, data[:i], nil
}
}
return 0, nil, nil
})
for scanner.Scan() {
fmt.Println("Fruit:", scanner.Text())
}
}
Scanning Workflow
graph TD
A[Open Data Source] --> B[Create Scanner]
B --> C{Scanning Strategy}
C -->|Line| D[Process Line by Line]
C -->|Delimiter| E[Split with Custom Delimiter]
D --> F[Apply Business Logic]
E --> F
F --> G[Collect/Transform Data]
G --> H[Handle Errors]
3. Configuration File Parsing
func parseConfigFile(filename string) (map[string]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
config := make(map[string]string)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
config[key] = value
}
}
return config, scanner.Err()
}
Best Practices
- Choose appropriate scanning method
- Handle potential errors
- Optimize memory usage
- Close resources properly
LabEx recommends mastering these scanning techniques for efficient Golang development.