Skip to content

Commit

Permalink
Fix URL parsing (#79)
Browse files Browse the repository at this point in the history
* Fix URL parsing

Get rid of schemify and let url.Parse do the heavy lifting.

* Add go test to travis
  • Loading branch information
moorereason authored and davecheney committed Sep 27, 2016
1 parent 28be964 commit c217740
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 11 deletions.
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ install:
script:
- go vet $(go list ./... | grep -v "vendor")
- go build github.com/davecheney/httpstat
- go test github.com/davecheney/httpstat
- ./httpstat http://dave.cheney.net/
- ./httpstat http://dave.cheney.net:80/
- ./httpstat -X POST -d 'post' http://httpbin.org/post
Expand All @@ -33,3 +34,5 @@ script:
- ./httpstat google.com
- ./httpstat google.com:80
- ./httpstat google.com:443
- ./httpstat golang.org:80/dl
- ./httpstat golang.org:443/dl
23 changes: 12 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,21 @@ func main() {
}

func parseURL(uri string) *url.URL {
url, err := url.Parse(schemify(uri))
if !strings.Contains(uri, "://") && !strings.HasPrefix(uri, "//") {
uri = "//" + uri
}

url, err := url.Parse(uri)
if err != nil {
log.Fatalf("could not parse url %q: %v", uri, err)
}

if url.Scheme == "" {
url.Scheme = "http"
if !strings.HasSuffix(url.Host, ":80") {
url.Scheme += "s"
}
}
return url
}

Expand All @@ -128,16 +139,6 @@ func headerKeyValue(h string) (string, string) {
return strings.TrimRight(h[:i], " "), strings.TrimLeft(h[i:], " :")
}

func schemify(uri string) string {
if !strings.Contains(uri, "://") {
if strings.HasSuffix(uri, ":80") {
return "http://" + uri
}
return "https://" + uri
}
return uri
}

func getHostPort(url *url.URL) (string, string, string) {
scheme := url.Scheme
URLHost := url.Host
Expand Down
24 changes: 24 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import "testing"

func TestParseURL(t *testing.T) {
tests := []struct {
in string
want string
}{
{"https://golang.org", "https://golang.org"},
{"https://golang.org:443/test", "https://golang.org:443/test"},
{"localhost:8080/test", "https://localhost:8080/test"},
{"localhost:80/test", "http://localhost:80/test"},
{"//localhost:8080/test", "https://localhost:8080/test"},
{"//localhost:80/test", "http://localhost:80/test"},
}

for _, test := range tests {
u := parseURL(test.in)
if u.String() != test.want {
t.Errorf("Given: %s\nwant: %s\ngot: %s", test.in, test.want, u.String())
}
}
}

0 comments on commit c217740

Please sign in to comment.