Skip to content

Instantly share code, notes, and snippets.

@prl900
Created February 3, 2018 11:51
Show Gist options
  • Save prl900/9566a8bfa0c688473a91aee67ea29338 to your computer and use it in GitHub Desktop.
Save prl900/9566a8bfa0c688473a91aee67ea29338 to your computer and use it in GitHub Desktop.
Go CSV parser sample code
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
const csvFile = "CSVFile.csv"
type Person struct {
Name, Phone, Job string
}
func validate(persons []Person) bool {
bob := false
dave := false
for _, person := range persons {
fmt.Println("----", person)
if person.Name == "Bob" {
bob = true
}
if person.Name == "Dave" && person.Phone == "0400 001 123" {
dave = true
}
}
return len(persons) == 4 && bob && dave
}
func personParser(path string) ([]Person, error) {
persons := []Person{}
f, _ := os.Open(csvFile)
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Scan()
for scanner.Scan() {
fields := strings.Split(strings.Trim(scanner.Text(), "\r"), ",")
if len(fields) != 3 {
return persons, fmt.Errorf("Unexpected number of fields in CSV line")
}
persons = append(persons, Person{Name: fields[0], Phone: fields[1], Job: fields[2]})
}
return persons, nil
}
func main() {
persons, err := personParser(csvFile)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(validate(persons))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment