Skip to content

Commit

Permalink
为钩子添加起止时间
Browse files Browse the repository at this point in the history
  • Loading branch information
blusewang committed Sep 12, 2021
1 parent 77bb26a commit 78d3fc4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
8 changes: 5 additions & 3 deletions http_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import (
"bytes"
"io/ioutil"
"net/http"
"time"
)

var _cli *http.Client
var _hook func(req *http.Request, reqBody []byte, res *http.Response, err error)
var _hook func(req *http.Request, reqBody []byte, res *http.Response, startAt time.Time, stopAt time.Time, err error)

type mt struct {
t http.Transport
Expand All @@ -25,9 +26,10 @@ func (m *mt) RoundTrip(req *http.Request) (res *http.Response, err error) {
reqBody, _ = ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewReader(reqBody))
}
t := time.Now()
res, err = m.t.RoundTrip(req)
if _hook != nil {
_hook(req, reqBody, res, err)
_hook(req, reqBody, res, t, time.Now(), err)
}
return
}
Expand All @@ -39,6 +41,6 @@ func client() *http.Client {
return _cli
}

func RegisterHook(hook func(req *http.Request, reqBody []byte, res *http.Response, err error)) {
func RegisterHook(hook func(req *http.Request, reqBody []byte, res *http.Response, startAt time.Time, stopAt time.Time, err error)) {
_hook = hook
}
5 changes: 5 additions & 0 deletions http_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,8 @@ func TestMt_RoundTrip(t *testing.T) {
}
mch.NewMchReq(mch_api.PayOrderQuery)
}

func TestRegisterHook(t *testing.T) {
log.SetFlags(log.Ltime | log.Lshortfile)
log.Println(client().Get("https://httpbin.org/delay/6"))
}

0 comments on commit 78d3fc4

Please sign in to comment.