You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context_template.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "context"
  6. "errors"
  7. "time"
  8. "code.gitea.io/gitea/modules/log"
  9. )
  10. var _ context.Context = TemplateContext(nil)
  11. func NewTemplateContext(ctx context.Context) TemplateContext {
  12. return TemplateContext{"_ctx": ctx}
  13. }
  14. func (c TemplateContext) parentContext() context.Context {
  15. return c["_ctx"].(context.Context)
  16. }
  17. func (c TemplateContext) Deadline() (deadline time.Time, ok bool) {
  18. return c.parentContext().Deadline()
  19. }
  20. func (c TemplateContext) Done() <-chan struct{} {
  21. return c.parentContext().Done()
  22. }
  23. func (c TemplateContext) Err() error {
  24. return c.parentContext().Err()
  25. }
  26. func (c TemplateContext) Value(key any) any {
  27. return c.parentContext().Value(key)
  28. }
  29. // DataRaceCheck checks whether the template context function "ctx()" returns the consistent context
  30. // as the current template's rendering context (request context), to help to find data race issues as early as possible.
  31. // When the code is proven to be correct and stable, this function should be removed.
  32. func (c TemplateContext) DataRaceCheck(dataCtx context.Context) (string, error) {
  33. if c.parentContext() != dataCtx {
  34. log.Error("TemplateContext.DataRaceCheck: parent context mismatch\n%s", log.Stack(2))
  35. return "", errors.New("parent context mismatch")
  36. }
  37. return "", nil
  38. }