Documentation
¶
Overview ¶
Package jmespath extracts data from events with JMESPath expressions, plus the functions Powertools adds to decode what AWS event sources encode:
- powertools_json(string) parses a JSON string;
- powertools_base64(string) decodes base64 into a UTF-8 string;
- powertools_base64_gzip(string) decodes base64, then gunzips it.
The envelope constants are the expressions that unwrap the payload of the common event sources, as Powertools Python names them. Validation, idempotency, the logger's correlation id and feature flags all accept these expressions.
Expressions follow JMESPath Community Edition, a superset of the JMESPath specification Powertools Python implements.
Index ¶
Examples ¶
Constants ¶
const ( APIGatewayREST = "powertools_json(body)" APIGatewayHTTP = APIGatewayREST SQS = "Records[*].powertools_json(body)" SNS = "Records[0].Sns.Message | powertools_json(@)" EventBridge = "detail" CloudWatchEventsSchedule = EventBridge KinesisDataStream = "Records[*].kinesis.powertools_json(powertools_base64(data))" CloudWatchLogs = "awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]" S3SNSSQS = "Records[*].powertools_json(body).powertools_json(Message).Records[0]" S3SQS = "Records[*].powertools_json(body).Records[0]" S3SNSKinesisFirehose = "records[*].powertools_json(powertools_base64(data)).powertools_json(Message).Records[0]" S3KinesisFirehose = "records[*].powertools_json(powertools_base64(data)).Records[0]" S3EventBridgeSQS = "Records[*].powertools_json(body).detail" )
The envelopes of the common event sources.
const MaxDecompressedSize = 128 << 20
MaxDecompressedSize bounds what powertools_base64_gzip inflates, so that a small malicious payload cannot exhaust the function's memory.
Variables ¶
var ( // ErrNotUTF8 reports decoded bytes that are not UTF-8 text. ErrNotUTF8 = errors.New("decoded data is not valid UTF-8") // ErrTooLarge reports gzip data that inflates beyond MaxDecompressedSize. ErrTooLarge = errors.New("decompressed data is too large") )
Errors of the Powertools functions.
var ErrInvalidEnvelope = errors.New("invalid envelope expression")
ErrInvalidEnvelope is what every failure to compile or evaluate an expression matches with errors.Is.
Functions ¶
func Generic ¶
Generic turns data into the decoded JSON value JMESPath works on: raw JSON is parsed, anything else is marshalled and parsed back, so that structs are seen through their JSON field names.
func Query ¶
Query evaluates expression against data and returns what it selects: Powertools Python's jmespath_utils.query.
Example ¶
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/alessandrolattao/powertools-lambda-go/jmespath"
)
func main() {
event := events.APIGatewayV2HTTPRequest{Body: `{"customerId":"c-42"}`}
payload, err := jmespath.Query(event, jmespath.APIGatewayHTTP+".customerId")
if err != nil {
panic(err)
}
fmt.Println(payload)
}
Output: c-42
func QueryAs ¶
QueryAs evaluates expression against data and decodes the selection into a T.
Example ¶
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/alessandrolattao/powertools-lambda-go/jmespath"
)
func main() {
type order struct {
ID string `json:"id"`
}
event := events.SQSEvent{Records: []events.SQSMessage{{Body: `{"id":"o-1"}`}, {Body: `{"id":"o-2"}`}}}
orders, err := jmespath.QueryAs[[]order](event, jmespath.SQS)
if err != nil {
panic(err)
}
fmt.Println(orders)
}
Output: [{o-1} {o-2}]
Types ¶
type Arg ¶
type Arg struct {
// Types lists the types the argument accepts.
Types []Type
// Variadic lets the last argument repeat.
Variadic bool
// Optional lets the argument be left out.
Optional bool
}
Arg declares one argument of a custom function.
type EnvelopeError ¶
EnvelopeError reports an expression that could not be compiled, or could not be evaluated against the data it was given.
func (*EnvelopeError) Error ¶
func (e *EnvelopeError) Error() string
func (*EnvelopeError) Is ¶
func (*EnvelopeError) Is(target error) bool
Is makes every EnvelopeError match ErrInvalidEnvelope.
type Expression ¶
type Expression struct {
// contains filtered or unexported fields
}
Expression is a compiled JMESPath expression. It is safe for concurrent use: compile it once, at package level or in init, and search many times.
func Compile ¶
func Compile(expression string, opts ...Option) (*Expression, error)
Compile parses expression, with the Powertools functions and any custom one available to it.
Example ¶
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/alessandrolattao/powertools-lambda-go/jmespath"
)
func main() {
// Compile once, search on every invocation.
userID := jmespath.MustCompile("requestContext.authorizer.jwt.claims.sub")
event := events.APIGatewayV2HTTPRequest{RequestContext: events.APIGatewayV2HTTPRequestContext{
Authorizer: &events.APIGatewayV2HTTPRequestContextAuthorizerDescription{
JWT: &events.APIGatewayV2HTTPRequestContextAuthorizerJWTDescription{
Claims: map[string]string{"sub": "user-7"},
},
},
}}
sub, err := userID.Search(event)
if err != nil {
panic(err)
}
fmt.Println(sub)
}
Output: user-7
func MustCompile ¶
func MustCompile(expression string, opts ...Option) *Expression
MustCompile is Compile for expressions known to be valid; it panics otherwise.
func (*Expression) Search ¶
func (e *Expression) Search(data any) (any, error)
Search evaluates the expression against data. Data is a decoded JSON value, a struct or map that marshals to JSON (an aws-lambda-go event), or raw JSON ([]byte, jsontext.Value). It returns the selected value as a decoded JSON value, nil when nothing matches.
func (*Expression) String ¶
func (e *Expression) String() string
String returns the expression's source.
type Function ¶
Function is a custom JMESPath function, for formats the built-in functions do not decode. It receives the arguments decoded as JSON values (nil, bool, float64, string, []any, map[string]any) and returns one.
type Option ¶
type Option func(*options)
Option configures how an expression is compiled.
func WithFunctions ¶
WithFunctions adds custom functions next to the built-in and the Powertools ones.