I
I
impressive172020-12-29 16:39:04
go
impressive17, 2020-12-29 16:39:04

How to create a new context from the old one ignoring context break in go?

There is a context with kenzel. I need to create (inherit) a new context from it without a kenzel and not lose information (not Background() in general).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-12-29
@ghostiam

Wrap the context in an irrevocable one.

// WithoutCancel returns a context that is never canceled.
func WithoutCancel(ctx context.Context) context.Context {
  return noCancel{ctx: ctx}
}

type noCancel struct {
  ctx context.Context
}

func (c noCancel) Deadline() (time.Time, bool)       { return time.Time{}, false }
func (c noCancel) Done() <-chan struct{}             { return nil }
func (c noCancel) Err() error                        { return nil }
func (c noCancel) Value(key interface{}) interface{} { return c.ctx.Value(key) }

Call something like this:
package main

import (
  "context"
  "time"
)

func main() {
  ctx := context.Background()
  ctx, c := context.WithTimeout(ctx, 100*time.Millisecond)
  defer c()

  ctxNo := WithoutCancel(ctx)
  ...
}

If a new timeout is set after WithoutCancel, then the new timeout will work and will not be canceled by the timeout that could have been before WithoutCancel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question