From 2e947c76e1f9e1adfbdfd4b5b9346756b5839d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristoffer=20Peterha=CC=88nsel?= Date: Tue, 9 Feb 2016 14:17:56 +0100 Subject: [PATCH] Fix fragment parsing so it won't get url encoded if there is no query in front of it --- uri.go | 38 ++++++++++++++++++++++++++++---------- uri_test.go | 1 + 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/uri.go b/uri.go index 32dcf65..dd28d3d 100644 --- a/uri.go +++ b/uri.go @@ -203,23 +203,41 @@ func (x *URI) parse(host, uri []byte, h *RequestHeader) { lowercaseBytes(x.host) b := uri - n := bytes.IndexByte(b, '?') - if n < 0 { + queryIndex := bytes.IndexByte(b, '?') + fragmentIndex := bytes.IndexByte(b, '#') + // Ignore query in fragment part + if fragmentIndex >= 0 && queryIndex > fragmentIndex { + queryIndex = -1 + } + + if queryIndex < 0 && fragmentIndex < 0 { x.pathOriginal = append(x.pathOriginal, b...) x.path = normalizePath(x.path, b) return } - x.pathOriginal = append(x.pathOriginal, b[:n]...) - x.path = normalizePath(x.path, x.pathOriginal) - b = b[n+1:] - n = bytes.IndexByte(b, '#') - if n >= 0 { - x.hash = append(x.hash, b[n+1:]...) - b = b[:n] + if queryIndex >= 0 { + // Path is everything up to the start of the query + x.pathOriginal = append(x.pathOriginal, b[:queryIndex]...) + x.path = normalizePath(x.path, x.pathOriginal) + + if fragmentIndex < 0 { + x.queryString = append(x.queryString, b[queryIndex+1:]...) + } else { + x.queryString = append(x.queryString, b[queryIndex+1:fragmentIndex]...) + } } - x.queryString = append(x.queryString, b...) + if fragmentIndex >= 0 { + if queryIndex < 0 { + // Path is up to the start of fragment. Unless a query was before it + x.pathOriginal = append(x.pathOriginal, b[:fragmentIndex]...) + x.path = normalizePath(x.path, x.pathOriginal) + } + + x.hash = append(x.hash, b[fragmentIndex+1:]...) + b = b[:fragmentIndex] + } } func normalizePath(dst, src []byte) []byte { diff --git a/uri_test.go b/uri_test.go index 71191cd..5cbab28 100644 --- a/uri_test.go +++ b/uri_test.go @@ -52,6 +52,7 @@ func TestURIUpdate(t *testing.T) { testURIUpdate(t, "http://xx/a/b/c/d", "../qwe/p?zx=34", "http://xx/a/b/qwe/p?zx=34") testURIUpdate(t, "https://qqq/aaa.html?foo=bar", "?baz=434&aaa", "https://qqq/aaa.html?baz=434&aaa") testURIUpdate(t, "http://foo.bar/baz", "~a/%20b=c,тест?йцу=ке", "http://foo.bar/~a/%20b=c,%D1%82%D0%B5%D1%81%D1%82?йцу=ке") + testURIUpdate(t, "http://foo.bar/baz", "/qwe#fragment", "http://foo.bar/qwe#fragment") } func testURIUpdate(t *testing.T, base, update, result string) {