Skip to content

Instantly share code, notes, and snippets.

@skrater
Created May 12, 2020 18:17
Show Gist options
  • Save skrater/867ee4473c5c7ad92bc514dbfd263543 to your computer and use it in GitHub Desktop.
Save skrater/867ee4473c5c7ad92bc514dbfd263543 to your computer and use it in GitHub Desktop.
Seeks UTF-8 BOM before reading CSV
package main
import (
"io"
"bytes"
)
var bom = []byte("\xef\xbb\xbf")
func trapBOM(rws io.ReadWriteSeeker) error {
fileBom := make([]byte, len(bom))
_, err := rws.Read(fileBom)
if err != nil {
return err
}
if bytes.Compare(bom, fileBom) != 0 {
return nil
}
_, err = rws.Seek(int64(len(bom)), io.SeekStart)
if err != nil {
return err
}
return nil
}
func main() {
f, err := os.Open("file-wih-bom.csv")
if err != nil {
panic(err)
}
defer f.Close()
err = trapBOM(f)
if err != nil {
panic(err)
}
records, err := csv.NewReader(r).ReadAll()
if err != nil {
panic(err)
}
fmt.Println(records)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment