feed refactoring

This commit is contained in:
Nazar Kanaev 2021-03-22 21:12:58 +00:00
parent e78c028d20
commit 7ca9415322
2 changed files with 28 additions and 23 deletions

View File

@ -1,6 +1,7 @@
package feed
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
@ -12,11 +13,10 @@ var UnknownFormat = errors.New("unknown feed format")
type processor func(r io.Reader) (*Feed, error)
func detect(lookup string) (string, processor) {
func sniff(lookup string) (string, processor) {
lookup = strings.TrimSpace(lookup)
if lookup[0] == '{' {
return "json", ParseJSON
}
switch lookup[0] {
case '<':
decoder := xml.NewDecoder(strings.NewReader(lookup))
for {
token, _ := decoder.Token()
@ -34,20 +34,25 @@ func detect(lookup string) (string, processor) {
}
}
}
case '{':
return "json", ParseJSON
}
return "", nil
}
func Parse(r io.Reader) (*Feed, error) {
var x [1024]byte
numread, err := r.Read(x[:])
chunk := make([]byte, 64)
numread, err := r.Read(chunk)
fmt.Println(numread, err)
if err != nil {
return nil, fmt.Errorf("Failed to read: %s", err)
}
_, callback := detect(string(x[:]))
_, callback := sniff(string(chunk))
if callback == nil {
return nil, UnknownFormat
}
r = io.MultiReader(bytes.NewReader(chunk), r)
return callback(r)
}

View File

@ -2,7 +2,7 @@ package feed
import "testing"
func TestDetect(t *testing.T) {
func TestSniff(t *testing.T) {
testcases := [][2]string{
{
`<?xml version="1.0"?><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"></rdf:RDF>`,
@ -26,7 +26,7 @@ func TestDetect(t *testing.T) {
},
}
for _, testcase := range testcases {
have, _ := detect(testcase[0])
have, _ := sniff(testcase[0])
want := testcase[1]
if want != have {
t.Log(testcase[0])