From be49d3027a6d64c4e8d5c4a9d99e8173b98a8743 Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Fri, 19 Feb 2016 18:53:13 +0200 Subject: [PATCH] Allow updating request's RequestURI and Host header via Request.URI() --- http.go | 2 +- http_test.go | 22 ++++++++++++++++++++++ uri.go | 2 +- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/http.go b/http.go index 1e99d33..8dd2fee 100644 --- a/http.go +++ b/http.go @@ -896,7 +896,7 @@ func (req *Request) onlyMultipartForm() bool { // // See also WriteTo. func (req *Request) Write(w *bufio.Writer) error { - if len(req.Header.Host()) == 0 { + if len(req.Header.Host()) == 0 || req.parsedURI { uri := req.URI() host := uri.Host() if len(host) == 0 { diff --git a/http_test.go b/http_test.go index e35a52f..eb01db5 100644 --- a/http_test.go +++ b/http_test.go @@ -11,6 +11,28 @@ import ( "testing" ) +func TestRequestUpdateURI(t *testing.T) { + var r Request + r.Header.SetHost("aaa.bbb") + r.SetRequestURI("/lkjkl/kjl") + + // Modify request uri and host via URI() object and make sure + // the requestURI and Host header are properly updated + u := r.URI() + u.SetPath("/123/432.html") + u.SetHost("foobar.com") + a := u.QueryArgs() + a.Set("aaa", "bcse") + + s := r.String() + if !strings.HasPrefix(s, "GET /123/432.html?aaa=bcse") { + t.Fatalf("cannot find %q in %q", "GET /123/432.html?aaa=bcse", s) + } + if strings.Index(s, "\r\nHost: foobar.com\r\n") < 0 { + t.Fatalf("cannot find %q in %q", "\r\nHost: foobar.com\r\n", s) + } +} + func TestRequestBodyStreamMultipleBodyCalls(t *testing.T) { var r Request diff --git a/uri.go b/uri.go index d057e0e..49b30a9 100644 --- a/uri.go +++ b/uri.go @@ -122,7 +122,7 @@ func (u *URI) Path() []byte { // SetPath sets URI path. func (u *URI) SetPath(path string) { - u.pathOriginal = append(u.pathOriginal, path...) + u.pathOriginal = append(u.pathOriginal[:0], path...) u.path = normalizePath(u.path, u.pathOriginal) }