This commit is contained in:
Laurent Ulrich
2024-07-06 21:03:35 +02:00
parent 7d521b3d11
commit f5c589127a
4 changed files with 50 additions and 172 deletions

48
csvparser.go Normal file
View File

@@ -0,0 +1,48 @@
package csvparser
import (
"fmt"
"strings"
"unicode/utf8"
)
type Parser struct {
enclosers [][]rune
delimiter rune
fields []string
}
func (p *Parser) Initialize(delimiter string, enclosers []string, lineFormat string) error {
if utf8.RuneCountInString(delimiter) != 1 {
return fmt.Errorf("delimiter shoud be 1 char length")
}
p.enclosers = make([][]rune, 0)
for _, str := range enclosers {
p.enclosers = append(p.enclosers, []rune(str))
}
p.delimiter = []rune(delimiter)[0]
for _, pair := range enclosers {
if utf8.RuneCountInString(pair) != 2 {
return fmt.Errorf("encoloser should contain two characters: %s", pair)
}
}
// line format is in the form of: field1 field2 ignore ...
// if field name is ignore, it is parsed but not retained
p.fields = strings.Split(lineFormat, " ")
return nil
}
func (p *Parser) Parse(line string) (map[string]string, error) {
ret := make(map[string]string)
for index, r := range line {
if r == p.delimiter {
}
for _, encloser := range p.enclosers {
runes = []rune(encloser)
}
}
return ret, nil
}