service.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package httpc
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/wuntsong-org/go-zero-plus/core/breaker"
  6. )
  7. type (
  8. // Option is used to customize the *http.Client.
  9. Option func(r *http.Request) *http.Request
  10. // Service represents a remote HTTP service.
  11. Service interface {
  12. // Do sends an HTTP request with the given arguments and returns an HTTP response.
  13. Do(ctx context.Context, method, url string, data any) (*http.Response, error)
  14. // DoRequest sends a HTTP request to the service.
  15. DoRequest(r *http.Request) (*http.Response, error)
  16. }
  17. namedService struct {
  18. name string
  19. cli *http.Client
  20. opts []Option
  21. }
  22. )
  23. // NewService returns a remote service with the given name.
  24. // opts are used to customize the *http.Client.
  25. func NewService(name string, opts ...Option) Service {
  26. return NewServiceWithClient(name, http.DefaultClient, opts...)
  27. }
  28. // NewServiceWithClient returns a remote service with the given name.
  29. // opts are used to customize the *http.Client.
  30. func NewServiceWithClient(name string, cli *http.Client, opts ...Option) Service {
  31. return namedService{
  32. name: name,
  33. cli: cli,
  34. opts: opts,
  35. }
  36. }
  37. // Do sends an HTTP request with the given arguments and returns an HTTP response.
  38. func (s namedService) Do(ctx context.Context, method, url string, data any) (*http.Response, error) {
  39. req, err := buildRequest(ctx, method, url, data)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return s.DoRequest(req)
  44. }
  45. // DoRequest sends an HTTP request to the service.
  46. func (s namedService) DoRequest(r *http.Request) (*http.Response, error) {
  47. return request(r, s)
  48. }
  49. func (s namedService) do(r *http.Request) (resp *http.Response, err error) {
  50. for _, opt := range s.opts {
  51. r = opt(r)
  52. }
  53. brk := breaker.GetBreaker(s.name)
  54. err = brk.DoWithAcceptable(func() error {
  55. resp, err = s.cli.Do(r)
  56. return err
  57. }, func(err error) bool {
  58. return err == nil && resp.StatusCode < http.StatusInternalServerError
  59. })
  60. return
  61. }