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

context.go 1.1 kB

1 year ago
1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package exec
  2. import (
  3. "context"
  4. "fmt"
  5. "gitlink.org.cn/cloudream/common/utils/reflect2"
  6. )
  7. var ErrValueNotFound = fmt.Errorf("value not found")
  8. type ExecContext struct {
  9. Context context.Context
  10. Values map[any]any
  11. }
  12. func NewExecContext() *ExecContext {
  13. return NewWithContext(context.Background())
  14. }
  15. func NewWithContext(ctx context.Context) *ExecContext {
  16. return &ExecContext{Context: ctx, Values: make(map[any]any)}
  17. }
  18. // error只会是ErrValueNotFound
  19. func (c *ExecContext) Value(key any) (any, error) {
  20. value, ok := c.Values[key]
  21. if !ok {
  22. return nil, ErrValueNotFound
  23. }
  24. return value, nil
  25. }
  26. func (c *ExecContext) SetValue(key any, value any) {
  27. c.Values[key] = value
  28. }
  29. func GetValueByType[T any](ctx *ExecContext) (T, error) {
  30. var ret T
  31. value, err := ctx.Value(reflect2.TypeOf[T]())
  32. if err != nil {
  33. return ret, err
  34. }
  35. ret, ok := value.(T)
  36. if !ok {
  37. return ret, fmt.Errorf("value is %T, not %T", value, ret)
  38. }
  39. return ret, nil
  40. }
  41. func SetValueByType[T any](ctx *ExecContext, value T) {
  42. ctx.SetValue(reflect2.TypeOf[T](), value)
  43. }