Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Runtime context is not reset before released to the pool #499

Open
lovromazgon opened this issue Feb 28, 2024 · 0 comments · May be fixed by #500
Open

Runtime context is not reset before released to the pool #499

lovromazgon opened this issue Feb 28, 2024 · 0 comments · May be fixed by #500

Comments

@lovromazgon
Copy link

lovromazgon commented Feb 28, 2024

When RuntimeContext is released back into the pool (here), it is not reset, which can cause the context passed to json.MarshalContext to be leaked into a different call to json.Marshal.

Failing test:

type Foo struct{}

func (Foo) MarshalJSON(ctx context.Context) ([]byte, error) {
	if ctx != nil {
		if val := ctx.Value("ctxKey"); val != nil {
			return []byte(`"` + val.(string) + `"`), nil
		}
	}
	return []byte(`"foo"`), nil
}

func TestContext(t *testing.T) {
	foo := Foo{}

	// first marshal with context
	ctx := context.WithValue(context.Background(), "ctxKey", "bar")
	out, _ := json.MarshalContext(ctx, foo)
	if string(out) != `"bar"` {
		t.Fatalf(`expected "bar", got %v`, string(out))
	}

	// second marshal without context (bug: it actually uses the previous context)
	out, _ = json.Marshal(foo)
	if string(out) != `"foo"` {
		t.Fatalf(`expected "foo", got %v`, string(out))
	}
}

Results in:

    context_test.go:34: expected "foo", got "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant