Skip to content

Instantly share code, notes, and snippets.

@52617365
Last active September 8, 2024 12:34
Show Gist options
  • Save 52617365/3f2eb0e8c3099b70559d0da8e19501c7 to your computer and use it in GitHub Desktop.
Save 52617365/3f2eb0e8c3099b70559d0da8e19501c7 to your computer and use it in GitHub Desktop.
A gist that shows how you how to create a custom split callback for the bufio scanner that lets you go until a delimiter that is more than one byte long.
// SplitAt returns a bufio.SplitFunc closure, splitting at a substring
// scanner.Split(SplitAt("\n# "))
func SplitAt(substring []byte) func(data []byte, atEOF bool) (advance int, token []byte, err error) {
return func(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Return nothing if at the end of the file and no data passed
if atEOF && len(data) == 0 {
return 0, nil, nil
}
// Find the index of the input of the separator substring
if i := bytes.Index(data, substring); i >= 0 {
return i + len(substring), data[0:i], nil
}
// If at the end of the file with data, return the data
if atEOF {
return len(data), data, nil
}
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment