-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
62 lines (51 loc) · 1.27 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package gopodcast
import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
)
type Parser struct {
HTTPClient *http.Client
UserAgent string
AuthCredentials *AuthCredentials
}
type AuthCredentials struct {
Username string
Password string
}
const defaultUserAgent = "gopodcast/1.0"
func NewParser() *Parser {
return &Parser{
HTTPClient: http.DefaultClient,
UserAgent: defaultUserAgent,
}
}
func (p *Parser) ParseFeedFromURL(ctx context.Context, url string) (*Podcast, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", p.UserAgent)
if p.AuthCredentials != nil && p.AuthCredentials.Username != "" && p.AuthCredentials.Password != "" {
req.SetBasicAuth(p.AuthCredentials.Username, p.AuthCredentials.Password)
}
res, err := p.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("non-200 http response '%d'", res.StatusCode)
}
return p.ParseFeed(res.Body)
}
func (p *Parser) ParseFeed(r io.Reader) (*Podcast, error) {
var feed xmlFixfeed
err := xml.NewDecoder(r).Decode(&feed)
if err != nil {
return nil, err
}
return feed.Translate().Channel, nil
}