http: fix transport crash when request URL is nil

Fixes #1602

R=rsc, petar-m
CC=golang-dev
https://golang.org/cl/4284043
This commit is contained in:
Brad Fitzpatrick 2011-03-11 09:54:31 -08:00
parent e6c9bccd33
commit 9554e67188
2 changed files with 46 additions and 0 deletions

View File

@ -36,6 +36,11 @@ type transport struct {
}
func (ct *transport) Do(req *Request) (resp *Response, err os.Error) {
if req.URL == nil {
if req.URL, err = ParseURL(req.RawURL); err != nil {
return
}
}
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme}
}

View File

@ -0,0 +1,41 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Tests for transport.go
package http_test
import (
"fmt"
. "http"
"http/httptest"
"io/ioutil"
"testing"
)
func TestTransportNilURL(t *testing.T) {
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "Hi")
}))
defer ts.Close()
req := new(Request)
req.URL = nil // what we're actually testing
req.Method = "GET"
req.RawURL = ts.URL
req.Proto = "HTTP/1.1"
req.ProtoMajor = 1
req.ProtoMinor = 1
// TODO(bradfitz): test &transport{} and not DefaultTransport
// once Transport is exported.
res, err := DefaultTransport.Do(req)
if err != nil {
t.Fatalf("unexpected Do error: %v", err)
}
body, err := ioutil.ReadAll(res.Body)
if g, e := string(body), "Hi"; g != e {
t.Fatalf("Expected response body of %q; got %q", e, g)
}
}