Skip to content

Commit

Permalink
feat: support Req()
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidCai1111 committed Mar 7, 2017
1 parent b0b1877 commit 215ce01
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 5 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
```
25 changes: 24 additions & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 {
Expand Down
15 changes: 11 additions & 4 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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))
}

0 comments on commit 215ce01

Please sign in to comment.