30 lines
673 B
Go
30 lines
673 B
Go
|
// Copyright © 2023 Roberto Hidalgo <event-gateway@un.rob.mx>
|
||
|
// SPDX-License-Identifier: Apache-2.0
|
||
|
package payload
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
type contextKey string
|
||
|
|
||
|
const ContextKey contextKey = "x-event-payload"
|
||
|
|
||
|
func FromContext(ctx context.Context) (*Payload, error) {
|
||
|
pf := ctx.Value(ContextKey)
|
||
|
if pf == nil {
|
||
|
return nil, fmt.Errorf("no payload found in context: %+v", ctx)
|
||
|
}
|
||
|
|
||
|
if parser, ok := pf.(Parser); ok {
|
||
|
return parser.Parse()
|
||
|
}
|
||
|
|
||
|
return nil, fmt.Errorf("value at %s is not a payload.Parser, it's a %+v", ContextKey, pf)
|
||
|
}
|
||
|
|
||
|
func Context(ctx context.Context, parser Parser) context.Context {
|
||
|
return context.WithValue(ctx, ContextKey, parser)
|
||
|
}
|