Created
February 3, 2018 11:51
-
-
Save prl900/9566a8bfa0c688473a91aee67ea29338 to your computer and use it in GitHub Desktop.
Go CSV parser sample code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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