request_handler.go 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. package client
  2. import (
  3. "context"
  4. "net/http"
  5. "sync"
  6. )
  7. // RequestHandler can be set to each Client instance and it should be
  8. // responsible to handle the begin and end states of each request.
  9. // Its BeginRequest fires right before the client talks to the server
  10. // and its EndRequest fires right after the client receives a response from the server.
  11. // If one of them return a non-nil error then the execution of client will stop and return that error.
  12. type RequestHandler interface {
  13. BeginRequest(context.Context, *http.Request) error
  14. EndRequest(context.Context, *http.Response, error) error
  15. }
  16. var (
  17. defaultRequestHandlers []RequestHandler
  18. mu sync.Mutex
  19. )
  20. // RegisterRequestHandler registers one or more request handlers
  21. // to be ran before and after of each request on all newly created Iris HTTP Clients.
  22. // Useful for Iris HTTP Client 3rd-party libraries
  23. // e.g. on init register a custom request-response lifecycle logging.
  24. func RegisterRequestHandler(reqHandlers ...RequestHandler) {
  25. mu.Lock()
  26. defaultRequestHandlers = append(defaultRequestHandlers, reqHandlers...)
  27. mu.Unlock()
  28. }