Browse Source

Check if href is a valid URL

renovate/configure
Yota Toyama 8 years ago
parent
commit
1481c37856
  1. 8
      main.go
  2. 10
      main_test.go

8
main.go

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url"
"os" "os"
"strings" "strings"
@ -61,7 +62,7 @@ func extractUrls(n *html.Node) map[string]bool {
if n.Type == html.ElementNode && n.Data == "a" { if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr { for _, a := range n.Attr {
if a.Key == "href" { if a.Key == "href" && isUrl(a.Val) {
ss[a.Val] = true ss[a.Val] = true
break break
} }
@ -76,6 +77,11 @@ func extractUrls(n *html.Node) map[string]bool {
return ss return ss
} }
func isUrl(s string) bool {
u, err := url.Parse(s)
return err == nil && (u.Scheme == "http" || u.Scheme == "https")
}
func getArgs() map[string]interface{} { func getArgs() map[string]interface{} {
usage := `Link checker for Markdown and HTML usage := `Link checker for Markdown and HTML

10
main_test.go

@ -47,3 +47,13 @@ func TestUrlParse(t *testing.T) {
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
assert.Equal(t, "", u.Scheme) assert.Equal(t, "", u.Scheme)
} }
func TestIsUrl(t *testing.T) {
for _, s := range []string{"http://google.com", "https://google.com"} {
assert.True(t, isUrl(s))
}
for _, s := range []string{"", "file-path"} {
assert.False(t, isUrl(s))
}
}

Loading…
Cancel
Save