Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ParseURL use Etag and LastModified #227

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 55 additions & 14 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io"
"net/http"
"strings"
"time"

"github.com/mmcdole/gofeed/atom"
"github.com/mmcdole/gofeed/json"
Expand Down Expand Up @@ -91,10 +92,21 @@ func (f *Parser) Parse(feed io.Reader) (*Feed, error) {
return nil, ErrFeedTypeNotDetected
}

type HTTPOptions struct {
Etag string
LastModified *time.Time
}

type HTTPFeed struct {
Feed *Feed
Etag string
LastModified *time.Time
}

// ParseURL fetches the contents of a given url and
// attempts to parse the response into the universal feed type.
func (f *Parser) ParseURL(feedURL string) (feed *Feed, err error) {
return f.ParseURLWithContext(feedURL, context.Background())
func (f *Parser) ParseURL(feedURL string, options HTTPOptions) (feed *HTTPFeed, err error) {
return f.ParseURLWithContext(feedURL, context.Background(), options)
}

// ParseURLWithContext fetches contents of a given url and
Expand All @@ -103,15 +115,24 @@ func (f *Parser) ParseURL(feedURL string) (feed *Feed, err error) {
// to use the BasicAuth during the HTTP call.
// It will be automatically added to the header of the request
// Request could be canceled or timeout via given context
func (f *Parser) ParseURLWithContext(feedURL string, ctx context.Context) (feed *Feed, err error) {
func (f *Parser) ParseURLWithContext(feedURL string, ctx context.Context, options HTTPOptions) (feed *HTTPFeed, err error) {
client := f.httpClient()
location := time.FixedZone("GMT", 0)

req, err := http.NewRequestWithContext(ctx, "GET", feedURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", f.UserAgent)

if options.Etag != "" {
req.Header.Set("If-None-Match", options.Etag)
}

if options.LastModified != nil {
req.Header.Set("If-Modified-Since", options.LastModified.In(location).Format(time.RFC1123))
}

if f.AuthConfig != nil && f.AuthConfig.Username != "" && f.AuthConfig.Password != "" {
req.SetBasicAuth(f.AuthConfig.Username, f.AuthConfig.Password)
}
Expand All @@ -122,23 +143,43 @@ func (f *Parser) ParseURLWithContext(feedURL string, ctx context.Context) (feed
return nil, err
}

if resp != nil {
defer func() {
ce := resp.Body.Close()
if ce != nil {
err = ce
}
}()
}

if resp.StatusCode < 200 || resp.StatusCode >= 300 {
if resp.StatusCode != 200 && resp.StatusCode != 206 && resp.StatusCode != 304 {
return nil, HTTPError{
StatusCode: resp.StatusCode,
Status: resp.Status,
}
}

return f.Parse(resp.Body)
httpFeed := HTTPFeed {
Etag: resp.Header.Get("Etag"),
LastModified: options.LastModified,
}

if lastModified := resp.Header.Get("Last-Modified"); lastModified != "" {
parsed, err := time.ParseInLocation(time.RFC1123, lastModified, location)
if err == nil {
httpFeed.LastModified = &parsed
}
}

if resp.StatusCode == 304 {
return &httpFeed, nil
}

defer func() {
ce := resp.Body.Close()
if ce != nil {
err = ce
}
}()

res, err := f.Parse(resp.Body)
if err != nil {
return nil, err
}
httpFeed.Feed = res

return &httpFeed, nil
}

// ParseString parses a feed XML string and into the
Expand Down
50 changes: 39 additions & 11 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,17 @@ func TestParser_ParseURL_Success(t *testing.T) {
server, client := mockServerResponse(200, string(f), 0)
fp := gofeed.NewParser()
fp.Client = client
feed, err := fp.ParseURL(server.URL)
feed, err := fp.ParseURL(server.URL, gofeed.HTTPOptions{})

if test.hasError {
assert.NotNil(t, err)
assert.Nil(t, feed)
} else {
assert.NotNil(t, feed)
assert.Nil(t, err)
assert.Equal(t, feed.FeedType, test.feedType)
assert.Equal(t, feed.Title, test.feedTitle)
assert.NotNil(t, feed)
assert.NotNil(t, feed.Feed)
assert.Equal(t, feed.Feed.FeedType, test.feedType)
assert.Equal(t, feed.Feed.Title, test.feedTitle)
}
}
}
Expand All @@ -154,15 +155,15 @@ func TestParser_ParseURLWithContext(t *testing.T) {
defer cancel()
fp := gofeed.NewParser()
fp.Client = client
_, err := fp.ParseURLWithContext(server.URL, ctx)
_, err := fp.ParseURLWithContext(server.URL, ctx, gofeed.HTTPOptions{})
assert.True(t, strings.Contains(err.Error(), ctx.Err().Error()))
}

func TestParser_ParseURL_Failure(t *testing.T) {
server, client := mockServerResponse(404, "", 0)
fp := gofeed.NewParser()
fp.Client = client
feed, err := fp.ParseURL(server.URL)
feed, err := fp.ParseURL(server.URL, gofeed.HTTPOptions{})

assert.NotNil(t, err)
assert.IsType(t, gofeed.HTTPError{}, err)
Expand All @@ -179,10 +180,36 @@ func TestParser_ParseURLWithContextAndBasicAuth(t *testing.T) {
Password: "bar",
}
fp.Client = client
_, err := fp.ParseURLWithContext(server.URL, ctx)
_, err := fp.ParseURLWithContext(server.URL, ctx, gofeed.HTTPOptions{})
assert.True(t, strings.Contains(err.Error(), ctx.Err().Error()))
}

func TestParser_ParseURL_Remote_Success(t *testing.T) {
testUrl := "https://developer.mozilla.org/en-US/blog/rss.xml"
fmt.Printf("Testing %s... ", testUrl)

fp := gofeed.NewParser()

feed1, err := fp.ParseURL("https://developer.mozilla.org/en-US/blog/rss.xml", gofeed.HTTPOptions{})
assert.Nil(t, err)
assert.NotNil(t, feed1)
assert.NotNil(t, feed1.Feed)

feed2, err := fp.ParseURL("https://developer.mozilla.org/en-US/blog/rss.xml", gofeed.HTTPOptions{
Etag: feed1.Etag,
})
assert.Nil(t, err)
assert.NotNil(t, feed2)
assert.Nil(t, feed2.Feed)

feed3, err := fp.ParseURL("https://developer.mozilla.org/en-US/blog/rss.xml", gofeed.HTTPOptions{
LastModified: feed1.LastModified,
})
assert.Nil(t, err)
assert.NotNil(t, feed3)
assert.Nil(t, feed3.Feed)
}

// to detect race conditions, run with go test -race
func TestParser_Concurrent(t *testing.T) {

Expand Down Expand Up @@ -218,6 +245,7 @@ func mockServerResponse(code int, body string, delay time.Duration) (*httptest.S
time.Sleep(delay)
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/xml")
w.Header().Set("Accept-Encoding", "gzip, deflate")
io.WriteString(w, body)
}))

Expand Down Expand Up @@ -249,11 +277,11 @@ func ExampleParser_Parse() {

func ExampleParser_ParseURL() {
fp := gofeed.NewParser()
feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml")
feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml", gofeed.HTTPOptions{})
if err != nil {
panic(err)
}
fmt.Println(feed.Title)
fmt.Println(feed.Feed.Title)
}

func ExampleParser_ParseString() {
Expand All @@ -276,9 +304,9 @@ func ExampleParserWithBasicAuth_ParseURL() {
Username: "foo",
Password: "bar",
}
feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml")
feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml", gofeed.HTTPOptions{})
if err != nil {
panic(err)
}
fmt.Println(feed.Title)
fmt.Println(feed.Feed.Title)
}