2020-07-26 17:09:05 +08:00
|
|
|
package contextx
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/mapping"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const contextTagKey = "ctx"
|
|
|
|
|
|
|
|
var unmarshaler = mapping.NewUnmarshaler(contextTagKey)
|
|
|
|
|
|
|
|
type contextValuer struct {
|
|
|
|
context.Context
|
|
|
|
}
|
|
|
|
|
2023-01-24 16:32:02 +08:00
|
|
|
func (cv contextValuer) Value(key string) (any, bool) {
|
2020-07-26 17:09:05 +08:00
|
|
|
v := cv.Context.Value(key)
|
|
|
|
return v, v != nil
|
|
|
|
}
|
|
|
|
|
2021-02-18 18:00:20 +08:00
|
|
|
// For unmarshals ctx into v.
|
2023-01-24 16:32:02 +08:00
|
|
|
func For(ctx context.Context, v any) error {
|
2020-07-26 17:09:05 +08:00
|
|
|
return unmarshaler.UnmarshalValuer(contextValuer{
|
|
|
|
Context: ctx,
|
|
|
|
}, v)
|
|
|
|
}
|