我正在尝试为向Web服务发出请求的程序包编写测试。我可能由于缺乏对TLS的了解而遇到问题。
目前,我的测试看起来像这样:
func TestSimple() { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, `{ "fake" : "json data here" }`) })) transport := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL) }, } // Client is the type in my package that makes requests client := Client{ c: http.Client{Transport: transport}, } client.DoRequest() // ... }
我的程序包具有一个要查询的Web服务基址的程序包变量(我希望它是一个常量。)。这是一个https URL。我在上面创建的测试服务器是纯HTTP,没有TLS。
默认情况下,我的测试失败,并显示错误“ tls:第一条记录看起来不像TLS握手”。
为了使它起作用,我的测试在进行查询之前将package变量更改为纯HTTP URL而不是https。
有没有办法解决?我可以将程序包变量设置为常量(https),然后将其设置为http.Transport“降级”为未加密的HTTP,还是httptest.NewTLSServer()改用?
http.Transport
httptest.NewTLSServer()
(当我尝试使用时,出现NewTLSServer()“ http:TLS握手错误,来自127.0.0.1:45678:tls:接收到长度为20037的超大记录”)
NewTLSServer()
net/http可以模仿,扩展或更改其中的大多数行为。尽管这http.Client是实现HTTP客户端语义的具体类型,但其所有字段都可以导出并可以自定义。
net/http
http.Client
Client.Transport特别是,可以替换该字段以使客户端执行任何操作,从使用自定义协议(例如ftp://或file://)到直接连接到本地处理程序(不生成HTTP协议字节或通过网络发送任何内容) )。
Client.Transport
客户端的功能,例如http.Get,所有利用导出的http.DefaultClient包变量(你可以修改),因此,利用这些方便的功能代码并 没有 ,例如,必须改变到在定制客户端变量调用方法。请注意,虽然在公共可用的库中修改全局行为是不合理的,但在应用程序和测试(包括库测试)中进行修改非常有用。
http.Get
http.DefaultClient
http://play.golang.org/p/afljO086iB包含一个自定义http.RoundTripper脚本,该自定义脚本重写了请求URL,以便将其路由到本地托管的httptest.Server;另一个示例将请求直接传递给http.Handler,以及自定义http.ResponseWriter实现,为了创建一个http.Response。第二种方法不像第一种方法那样努力(它没有填写Response值中的许多字段),但是效率更高,并且应该足够兼容以与大多数处理程序和客户端调用程序一起使用。
http.RoundTripper
httptest.Server
http.Handler
http.ResponseWriter
http.Response
上面链接的代码也包括在下面:
package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" "net/url" "os" "path" "strings" ) func Handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello %s\n", path.Base(r.URL.Path)) } func main() { s := httptest.NewServer(http.HandlerFunc(Handler)) u, err := url.Parse(s.URL) if err != nil { log.Fatalln("failed to parse httptest.Server URL:", err) } http.DefaultClient.Transport = RewriteTransport{URL: u} resp, err := http.Get("https://google.com/path-one") if err != nil { log.Fatalln("failed to send first request:", err) } fmt.Println("[First Response]") resp.Write(os.Stdout) fmt.Print("\n", strings.Repeat("-", 80), "\n\n") http.DefaultClient.Transport = HandlerTransport{http.HandlerFunc(Handler)} resp, err = http.Get("https://google.com/path-two") if err != nil { log.Fatalln("failed to send second request:", err) } fmt.Println("[Second Response]") resp.Write(os.Stdout) } // RewriteTransport is an http.RoundTripper that rewrites requests // using the provided URL's Scheme and Host, and its Path as a prefix. // The Opaque field is untouched. // If Transport is nil, http.DefaultTransport is used type RewriteTransport struct { Transport http.RoundTripper URL *url.URL } func (t RewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) { // note that url.URL.ResolveReference doesn't work here // since t.u is an absolute url req.URL.Scheme = t.URL.Scheme req.URL.Host = t.URL.Host req.URL.Path = path.Join(t.URL.Path, req.URL.Path) rt := t.Transport if rt == nil { rt = http.DefaultTransport } return rt.RoundTrip(req) } type HandlerTransport struct{ h http.Handler } func (t HandlerTransport) RoundTrip(req *http.Request) (*http.Response, error) { r, w := io.Pipe() resp := &http.Response{ Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Body: r, Request: req, } ready := make(chan struct{}) prw := &pipeResponseWriter{r, w, resp, ready} go func() { defer w.Close() t.h.ServeHTTP(prw, req) }() <-ready return resp, nil } type pipeResponseWriter struct { r *io.PipeReader w *io.PipeWriter resp *http.Response ready chan<- struct{} } func (w *pipeResponseWriter) Header() http.Header { return w.resp.Header } func (w *pipeResponseWriter) Write(p []byte) (int, error) { if w.ready != nil { w.WriteHeader(http.StatusOK) } return w.w.Write(p) } func (w *pipeResponseWriter) WriteHeader(status int) { if w.ready == nil { // already called return } w.resp.StatusCode = status w.resp.Status = fmt.Sprintf("%d %s", status, http.StatusText(status)) close(w.ready) w.ready = nil }