diff --git a/README.md b/README.md index 89ccbeb..69ce2cd 100644 --- a/README.md +++ b/README.md @@ -86,3 +86,12 @@ json, err = request. Proxy("http://myproxy.com:8080"). JSON() ``` + +### Convert to http.Request instance + +```go +req, err = request. + Post("http://mysite.com/form"). + Auth("name", "passwd"). + Req() +``` diff --git a/request.go b/request.go index b06f2a1..dd0aa59 100644 --- a/request.go +++ b/request.go @@ -19,7 +19,7 @@ import ( ) // Version is this package's version number. -const Version = "1.5.3" +const Version = "1.6.0" // Errors used by this package. var ( @@ -417,6 +417,29 @@ func (c *Client) End() (*Response, error) { return c.res, nil } +// Req returns the representing http.Request instance of this request. +// It is often used in wirting tests. +func (c *Client) Req() (*http.Request, error) { + if c.url == nil { + return nil, ErrLackURL + } + + if c.method == "" { + return nil, ErrLackMethod + } + + if c.err != nil { + return nil, c.err + } + + if err := c.assemble(); err != nil { + c.err = err + return nil, err + } + + return c.req, nil +} + // JSON sends the HTTP request and returns the reponse body with JSON format. func (c *Client) JSON(v ...interface{}) (interface{}, error) { if _, err := c.End(); err != nil { diff --git a/request_test.go b/request_test.go index 8eb21bb..e551f15 100644 --- a/request_test.go +++ b/request_test.go @@ -3,14 +3,12 @@ package request import ( "fmt" "net/http" + "net/http/cookiejar" + "net/http/httptest" "net/url" "testing" "time" - "net/http/httptest" - - "net/http/cookiejar" - "github.com/go-http-utils/headers" "github.com/stretchr/testify/suite" ) @@ -498,6 +496,15 @@ func (s *RequestSuite) TestProxyInvalidSocks5URL() { s.NotNil(err) } +func (s *RequestSuite) TestReq() { + req, err := s.c.Post(testHost + "/post"). + Accept("json"). + Req() + + s.Nil(err) + s.Equal(req.Header.Get(headers.Accept), "application/json") +} + func TestRequest(t *testing.T) { suite.Run(t, new(RequestSuite)) }