1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-10 05:25:58 +00:00

minor improvements

This commit is contained in:
Gerasimos (Makis) Maropoulos
2022-02-26 20:03:35 +02:00
parent 70a73ef80b
commit 09f494e406
4 changed files with 114 additions and 35 deletions

View File

@@ -0,0 +1,57 @@
package client
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
)
// See "Handler" client option.
type handlerTransport struct {
handler http.Handler
}
// RoundTrip completes the http.RoundTripper interface.
// It can be used to test calls to a server's handler.
func (t *handlerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
reqCopy := *req
if reqCopy.Proto == "" {
reqCopy.Proto = fmt.Sprintf("HTTP/%d.%d", reqCopy.ProtoMajor, reqCopy.ProtoMinor)
}
if reqCopy.Body != nil {
if reqCopy.ContentLength == -1 {
reqCopy.TransferEncoding = []string{"chunked"}
}
} else {
reqCopy.Body = ioutil.NopCloser(bytes.NewReader(nil))
}
if reqCopy.RequestURI == "" {
reqCopy.RequestURI = reqCopy.URL.RequestURI()
}
recorder := httptest.NewRecorder()
t.handler.ServeHTTP(recorder, &reqCopy)
resp := http.Response{
Request: &reqCopy,
StatusCode: recorder.Code,
Status: http.StatusText(recorder.Code),
Header: recorder.Result().Header,
}
if recorder.Flushed {
resp.TransferEncoding = []string{"chunked"}
}
if recorder.Body != nil {
resp.Body = ioutil.NopCloser(recorder.Body)
}
return &resp, nil
}

View File

@@ -35,6 +35,17 @@ func Timeout(d time.Duration) Option {
}
}
// Handler specifies an iris.Application or any http.Handler
// instance which can be tested using this Client.
//
// It registers a custom HTTP client transport
// which allows "fake calls" to the "h" server. Use it for testing.
func Handler(h http.Handler) Option {
return func(c *Client) {
c.HTTPClient.Transport = new(handlerTransport)
}
}
// PersistentRequestOptions adds one or more persistent request options
// that all requests made by this Client will respect.
func PersistentRequestOptions(reqOpts ...RequestOption) Option {