Skip to content

Commit 7e94697

Browse files
committed
discourse input url validation, fixes #17
1 parent 2133901 commit 7e94697

File tree

2 files changed

+12
-25
lines changed

2 files changed

+12
-25
lines changed

Diff for: internal/discourse/validate.go

+8-23
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,16 @@
11
package discourse
22

33
import (
4-
"errors"
5-
"net/url"
6-
"strconv"
7-
"strings"
4+
"fmt"
5+
"regexp"
86
)
97

10-
func effectiveUrl(rawUrl string) (string, error) {
11-
url, err := url.Parse(rawUrl)
12-
if err != nil {
13-
return "", err
14-
}
15-
16-
paths := strings.Split(url.Path, "/")
17-
if len(paths) != 4 {
18-
return "", errors.New("invalid url, does not enough paths")
19-
}
8+
var urlRegex = regexp.MustCompile(`http[s]?://[^/]+/t/[^/]+/[0-9]+`)
209

21-
if paths[1] != "t" {
22-
return "", errors.New("invalid url, does not have a `/t/` path")
23-
}
24-
25-
rawId := paths[3]
26-
if _, err = strconv.Atoi(rawId); err != nil {
27-
return "", errors.New("invalid url, does not end with a number")
10+
func effectiveUrl(rawUrl string) (string, error) {
11+
url := urlRegex.FindString(rawUrl)
12+
if url == "" {
13+
return "", fmt.Errorf("invalid url: %s", rawUrl)
2814
}
29-
30-
return url.String() + ".json", nil
15+
return url + ".json", nil
3116
}

Diff for: internal/discourse/validate_test.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import "testing"
44

55
func TestEffectiveUrl(t *testing.T) {
66
testUrls := map[string]string{
7-
"https://llllllll.co/t/disquiet-junto-project-0590-concrete-roots/62027": "https://llllllll.co/t/disquiet-junto-project-0590-concrete-roots/62027.json",
8-
"https://0x00sec.org/t/question-on-your-need-to-be-known/34563": "https://0x00sec.org/t/question-on-your-need-to-be-known/34563.json",
7+
"https://llllllll.co/t/disquiet-junto-project-0590-concrete-roots/62027": "https://llllllll.co/t/disquiet-junto-project-0590-concrete-roots/62027.json",
8+
"https://0x00sec.org/t/question-on-your-need-to-be-known/34563": "https://0x00sec.org/t/question-on-your-need-to-be-known/34563.json",
9+
"https://discourse.haskell.org/t/an-opportunity-that-i-couldnt-pass-up/7485/": "https://discourse.haskell.org/t/an-opportunity-that-i-couldnt-pass-up/7485.json",
10+
"https://discourse.haskell.org/t/an-opportunity-that-i-couldnt-pass-up/7485/3": "https://discourse.haskell.org/t/an-opportunity-that-i-couldnt-pass-up/7485.json",
911
}
1012
for rawUrl, expected := range testUrls {
1113
got, _ := effectiveUrl(rawUrl)

0 commit comments

Comments
 (0)