Created
January 4, 2019 21:37
-
-
Save earthboundkid/08979bc35c22e4b5ad9dd8628d5eb5f5 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"bufio" | |
"bytes" | |
"fmt" | |
) | |
const html = ` | |
<html> | |
<head> | |
<title>text</title> | |
</head> | |
<body> | |
<h1>more text</h1> | |
</body> | |
</html>` | |
func main() { | |
src := bytes.NewReader([]byte(html)) | |
scanner := bufio.NewScanner(src) | |
scanner.Split(splitHTML) | |
for scanner.Scan() { | |
fmt.Printf("token: %q\n", scanner.Text()) | |
} | |
fmt.Println(scanner.Err()) | |
} | |
func splitHTML(data []byte, atEOF bool) (advance int, token []byte, err error) { | |
tagStart := bytes.Index(data, []byte("<")) | |
if tagStart > 0 { | |
trimmed := bytes.TrimSpace(data[:tagStart]) | |
if len(trimmed) > 0 { | |
return tagStart, trimmed, nil | |
} | |
} | |
if tagStart == -1 { | |
if atEOF { | |
return 0, bytes.TrimSpace(data), bufio.ErrFinalToken | |
} else { | |
return 0, nil, nil | |
} | |
} | |
tagEnd := bytes.Index(data, []byte(">")) | |
if tagEnd == -1 { | |
if atEOF { | |
return 0, nil, fmt.Errorf("malformed tag: %q", string(data)) | |
} else { | |
return 0, nil, nil | |
} | |
} | |
return tagEnd + 1, data[tagStart : tagEnd+1], nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment