4

I have a custom http client, which has a default timeout value. The code is like this:

type Client struct {
  *http.Client
  timeout time.Duration
}

func (c *Client) Send(ctx context.Context, r *http.Request) (int, []byte, error) {
  // If ctx has timeout set, then don't change it.
  // Otherwise, create new context with ctx.WithTimeout(c.timeout)
}

How can I check if ctx has timeout set or not?

1 Answer 1

10

Check the bool return value from context.Deadline:

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

Deadline() (deadline time.Time, ok bool)
func (c *Client) Send(ctx context.Context, r *http.Request) (int, []byte, error) {
    if _, deadlineSet := ctx.Deadline(); !deadlineSet {
        ctx, _ = context.WithTimeout(ctx, c.timeout)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.