2020-01-02 05:39:52 +00:00
|
|
|
package httputil
|
|
|
|
|
2020-01-16 04:27:57 +00:00
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
)
|
2020-01-02 05:39:52 +00:00
|
|
|
|
|
|
|
type TransportWrapper struct {
|
2020-01-20 19:28:55 +00:00
|
|
|
Default http.RoundTripper
|
|
|
|
Pre func(*http.Request) error
|
2020-03-01 22:25:54 +00:00
|
|
|
Post func(*http.Request, *http.Response) error
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
2020-01-20 19:28:55 +00:00
|
|
|
var _ http.RoundTripper = (*TransportWrapper)(nil)
|
|
|
|
|
2020-01-02 05:39:52 +00:00
|
|
|
func NewTransportWrapper() *TransportWrapper {
|
|
|
|
return &TransportWrapper{
|
2020-01-20 19:28:55 +00:00
|
|
|
Default: http.DefaultTransport,
|
|
|
|
Pre: func(*http.Request) error { return nil },
|
2020-03-01 22:25:54 +00:00
|
|
|
Post: func(*http.Request, *http.Response) error { return nil },
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-01 22:25:54 +00:00
|
|
|
func (c *TransportWrapper) RoundTrip(req *http.Request) (r *http.Response, err error) {
|
2020-01-02 05:39:52 +00:00
|
|
|
if err := c.Pre(req); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-03-01 22:25:54 +00:00
|
|
|
r, err = c.Default.RoundTrip(req)
|
2020-01-02 05:39:52 +00:00
|
|
|
|
2020-03-01 22:25:54 +00:00
|
|
|
// Call Post regardless of error:
|
|
|
|
if postErr := c.Post(req, r); postErr != nil {
|
|
|
|
return r, postErr
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
2020-03-01 22:25:54 +00:00
|
|
|
return r, err
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|