Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added BOM support #26

Merged
merged 1 commit into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions csv_files/valid_bom.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
header1, header2, header3
line1, 1, 1.2
line2, 2, 2.3
line3, 3, 3.4
21 changes: 21 additions & 0 deletions load.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package csvtag

import (
"bytes"
"encoding/csv"
"fmt"
"io"
Expand Down Expand Up @@ -113,6 +114,8 @@ func LoadFromString(str string, destination interface{}, options ...CsvOptions)
// @param separator: the separator used in the csv file.
// @param header: the optional header if the file does not contain one.
func readFile(file io.Reader, separator rune, header []string) ([]string, [][]string, error) {
file = skipBOM(file)

// Create and configure the csv reader.
reader := csv.NewReader(file)
reader.TrimLeadingSpace = true
Expand Down Expand Up @@ -141,6 +144,24 @@ func readFile(file io.Reader, separator rune, header []string) ([]string, [][]st
return header, content, nil
}

// Skip the Byte Order Mark (BOM) if it exists.
// @param file: the io.Reader to read from.
func skipBOM(file io.Reader) io.Reader {
// Read the first 3 bytes.
bom := make([]byte, 3)
_, err := file.Read(bom)
if err != nil {
return file
}

// If the first 3 bytes are not the BOM, reset the reader.
if bom[0] != 0xEF || bom[1] != 0xBB || bom[2] != 0xBF {
return io.MultiReader(bytes.NewReader(bom), file)
}

return file
}

// Map the provided content to the destination using the header and the tags.
// @param header: the csv header to match with the struct's tags.
// @param content: the content to put in destination.
Expand Down
8 changes: 8 additions & 0 deletions load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ func TestValideFile(t *testing.T) {
}
}

func TestValideFileWithBOM(t *testing.T) {
tabT := []test{}
err := LoadFromPath("csv_files/valid_bom.csv", &tabT)
if err != nil || checkValues(tabT) {
t.Fail()
}
}

func TestBool(t *testing.T) {
tabT := []testBool{}
err := LoadFromPath("csv_files/bool.csv", &tabT)
Expand Down