Last active
September 8, 2024 12:34
-
-
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.
This file contains hidden or 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
// 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