feat: simplify httpc (#1748)
* feat: simplify httpc * chore: fix lint errors * chore: fix log url issue * chore: fix log url issue * refactor: handle resp & err in ResponseHandler * chore: remove unnecessary var names in return clausemaster v1.3.2
parent
e0fa8d820d
commit
78ea0769fd
@ -1,21 +1,44 @@
|
|||||||
package httpc
|
package httpc
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/zeromicro/go-zero/rest/httpc/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Do sends an HTTP request to the service assocated with the given key.
|
var interceptors = []internal.Interceptor{
|
||||||
func Do(key string, r *http.Request) (*http.Response, error) {
|
internal.LogInterceptor,
|
||||||
return NewService(key).Do(r)
|
}
|
||||||
|
|
||||||
|
// DoRequest sends an HTTP request and returns an HTTP response.
|
||||||
|
func DoRequest(r *http.Request) (*http.Response, error) {
|
||||||
|
return request(r, defaultClient{})
|
||||||
|
}
|
||||||
|
|
||||||
|
type (
|
||||||
|
client interface {
|
||||||
|
do(r *http.Request) (*http.Response, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultClient struct{}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (c defaultClient) do(r *http.Request) (*http.Response, error) {
|
||||||
|
return http.DefaultClient.Do(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func request(r *http.Request, cli client) (*http.Response, error) {
|
||||||
|
var respHandlers []internal.ResponseHandler
|
||||||
|
for _, interceptor := range interceptors {
|
||||||
|
var h internal.ResponseHandler
|
||||||
|
r, h = interceptor(r)
|
||||||
|
respHandlers = append(respHandlers, h)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get sends an HTTP GET request to the service assocated with the given key.
|
resp, err := cli.do(r)
|
||||||
func Get(key, url string) (*http.Response, error) {
|
for i := len(respHandlers) - 1; i >= 0; i-- {
|
||||||
return NewService(key).Get(url)
|
respHandlers[i](resp, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post sends an HTTP POST request to the service assocated with the given key.
|
return resp, err
|
||||||
func Post(key, url, contentType string, body io.Reader) (*http.Response, error) {
|
|
||||||
return NewService(key).Post(url, contentType, body)
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue