Skip to content

Commit

Permalink
Catch invalid/missing URLs in server config JSON
Browse files Browse the repository at this point in the history
url.Parse() accepts garbage like "" or "foo bar" without returning an
error. The resulting URLs don't work and cause errors later on, when
it's hard to tell where they came from. I'm working around this by
checking the parsed URL object for a non-empty Scheme component.
Added a utility function ParseURL that does this.
(See issue couchbase/sync_gateway#147)
  • Loading branch information
snej committed Oct 16, 2013
1 parent a230b9d commit 4a0afd5
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 6 deletions.
4 changes: 2 additions & 2 deletions pools.go
Expand Up @@ -186,7 +186,7 @@ func (b basicAuth) GetCredentials() (string, string) {
}

func basicAuthFromURL(us string) (ah AuthHandler) {
u, err := url.Parse(us)
u, err := ParseURL(us)
if err != nil {
return
}
Expand All @@ -200,7 +200,7 @@ func basicAuthFromURL(us string) (ah AuthHandler) {
// ConnectWithAuth connects to a couchbase cluster with the given
// authentication handler.
func ConnectWithAuth(baseU string, ah AuthHandler) (c Client, err error) {
c.BaseURL, err = url.Parse(baseU)
c.BaseURL, err = ParseURL(baseU)
if err != nil {
return
}
Expand Down
17 changes: 16 additions & 1 deletion util.go
@@ -1,6 +1,10 @@
package couchbase

import "strings"
import (
"fmt"
"net/url"
"strings"
)

// Return the hostname with the given suffix removed.
func CleanupHost(h, commonSuffix string) string {
Expand Down Expand Up @@ -32,3 +36,14 @@ func FindCommonSuffix(input []string) string {
}
return rv
}

// Some sanity-checking around URL.Parse, which is woefully trusting of bogus URL strings
// like "" or "foo bar".
func ParseURL(urlStr string) (url *url.URL, err error) {
url, err = url.Parse(urlStr)
if url != nil && url.Scheme == "" {
url = nil
err = fmt.Errorf("Invalid URL <%s>", urlStr)
}
return
}
2 changes: 1 addition & 1 deletion views.go
Expand Up @@ -36,7 +36,7 @@ func (b *Bucket) randomBaseURL() (*url.URL, error) {
return nil, errors.New("no couch rest URLs")
}
node := b.Nodes[rand.Intn(len(b.Nodes))]
u, err := url.Parse(node.CouchAPIBase)
u, err := ParseURL(node.CouchAPIBase)
if err == nil && b.pool != nil {
u.User = b.pool.client.BaseURL.User
}
Expand Down
3 changes: 1 addition & 2 deletions views_test.go
@@ -1,7 +1,6 @@
package couchbase

import (
"net/url"
"testing"
)

Expand Down Expand Up @@ -61,7 +60,7 @@ func TestViewURL(t *testing.T) {
continue
}

u, err := url.Parse(us)
u, err := ParseURL(us)
if err != nil {
t.Errorf("Failed on %v", test)
continue
Expand Down

0 comments on commit 4a0afd5

Please sign in to comment.