Created
January 21, 2025 14:56
-
-
Save muhammedkucukaslan/73f01d6628c6b842d5ece84fc3ab084f to your computer and use it in GitHub Desktop.
A Golang Function which takes a Reader and Returns a Map and an Error
This file contains 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
func CSVToMap(reader io.Reader) (map[string]string, error) { | |
csvReader := csv.NewReader(reader) | |
header, err := csvReader.Read() | |
if err != nil { | |
return nil, fmt.Errorf("failed to read header: %w", err) | |
} | |
if len(header) < 2 { | |
return nil, fmt.Errorf("CSV file must have at least two columns") | |
} | |
targetMap := make(map[string]string) | |
for { | |
record, err := csvReader.Read() | |
if err == io.EOF { | |
break | |
} | |
if err != nil { | |
return nil, fmt.Errorf("failed to read record: %w", err) | |
} | |
// Add here if you are not sure that every record has 2 line | |
// if len(record) < 2 { | |
// return nil, fmt.Errorf("invalid record format at line %d", len(symbols)+1) | |
// } | |
targetMap[record[0]] = record[1] | |
} | |
return targetMap, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment