Skip to content

v0.13.0: Interceptors

Compare
Choose a tag to compare
@mr-linch mr-linch released this 12 Mar 14:39
· 7 commits to main since this release
5cf133d

Interceptors are used to modify or process the request before it is sent to the server and the response before it is returned to the caller. It's like a [tgb.Middleware], but for outgoing requests.

All interceptors should be registered on the client before the request is made.

client := tg.New("<TOKEN>",
  tg.WithClientInterceptors(
    tg.Interceptor(func(ctx context.Context, req *tg.Request, dst any, invoker tg.InterceptorInvoker) error {
      started := time.Now()

      // before request
      err := invoker(ctx, req, dst)
      // after request

      log.Print("call %s took %s", req.Method, time.Since(started))

      return err
    }),
  ),
)

Arguments of the interceptor are:

  • ctx - context of the request;
  • req - request object tg.Request;
  • dst - pointer to destination for the response, can be nil if the request is made with DoVoid method;
  • invoker - function for calling the next interceptor or the actual request.

Contrib package has some useful interceptors:

Interceptors are called in the order they are registered.

Example of using retry flood interceptor: examples/retry-flood

Full Changelog: v0.12.0...v0.13.0