Skip to content

Commit

Permalink
Add area function
Browse files Browse the repository at this point in the history
  • Loading branch information
yyoshiki41 committed Nov 8, 2016
1 parent 21b3a56 commit 20a5fbd
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 1 deletion.
44 changes: 44 additions & 0 deletions area.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package radiko

import (
"net/http"

"golang.org/x/net/html"
)

const (
areaURL = "http://radiko.jp/area"
)

// AreaID returns areaID.
func AreaID() (string, error) {
resp, err := http.Get(areaURL)
if err != nil {
return "", err
}
defer resp.Body.Close()

doc, err := html.Parse(resp.Body)
if err != nil {
return "", err
}

return processSpanNode(doc), nil
}

func processSpanNode(n *html.Node) string {
var areaID string

var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "span" && len(n.Attr) > 0 {
areaID = n.Attr[0].Val
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(n)

return areaID
}
32 changes: 32 additions & 0 deletions area_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package radiko

import (
"strings"
"testing"

"golang.org/x/net/html"
)

func TestAreaID(t *testing.T) {
areaID, err := AreaID()
if err != nil {
t.Errorf("Failed to download player.swf: %s", err)
}
if areaID == "" {
t.Errorf("Invalid area id: %s", areaID)
}
}

func TestProcessSpanNode(t *testing.T) {
s := `document.write('<span class="JP13">TOKYO JAPAN</span>');`
doc, err := html.Parse(strings.NewReader(s))
if err != nil {
t.Errorf("Parse HTML: %s", err)
}

areaID := processSpanNode(doc)
if areaID != "JP13" {
t.Errorf("Failed to process span node.\nAreaID: %s",
areaID)
}
}
2 changes: 1 addition & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func New() (*Client, error) {
}

if httpClient == nil {
return nil, errors.New("HTTP Client is nil")
return nil, errors.New("A HTTP client is nil.")
}

return &Client{
Expand Down

0 comments on commit 20a5fbd

Please sign in to comment.