Created
May 12, 2020 18:17
-
-
Save skrater/867ee4473c5c7ad92bc514dbfd263543 to your computer and use it in GitHub Desktop.
Seeks UTF-8 BOM before reading CSV
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
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