-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (69 loc) · 2.33 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"encoding/json"
"errors"
"log"
"github.com/aws/aws-lambda-go/lambda"
)
// Event is a generic Event that the Lambda is invoked with.
type Event struct {
GenericField string
}
func main() {
lambda.Start(
StayToasty( // Ping event handler - returns if a ping is received.
ParseEvent( // Parse the standard event - return on error.
Process, // Process the standard event.
),
),
)
}
// HandlerFunc is a generic JSON Lambda handler used to chain middleware.
type HandlerFunc func(context.Context, json.RawMessage) (interface{}, error)
// MiddlewareFunc is a generic middleware example that takes in a HandlerFunc
// and calls the next middleware in the chain.
func MiddlewareFunc(next HandlerFunc) HandlerFunc {
return HandlerFunc(func(ctx context.Context, data json.RawMessage) (interface{}, error) {
return next(ctx, data)
})
}
// StayToasty is a middleware that checks for a ping and returns if it was a ping
// otherwise it will call the next middleware in the chain.
// Can be used to keep a Lambda function warm.
func StayToasty(next HandlerFunc) HandlerFunc {
type ping struct {
Ping string `json:"ping"`
}
return HandlerFunc(func(ctx context.Context, data json.RawMessage) (interface{}, error) {
var p ping
// If unmarshal into the ping struct is successful and there was a value in ping, return out.
if err := json.Unmarshal(data, &p); err == nil && p.Ping != "" {
log.Println("ping")
return "pong", nil
}
// Otherwise it's a regular request, call the next middleware.
return next(ctx, data)
})
}
// ParseEvent is a middleware that unmarshals an Event before passing control.
func ParseEvent(h EventHandler) HandlerFunc {
return HandlerFunc(func(ctx context.Context, data json.RawMessage) (interface{}, error) {
var event Event
if err := json.Unmarshal(data, &event); err != nil {
return nil, err
}
if event.GenericField == "" {
return nil, errors.New("GenericField must be populated")
}
return h(&ctx, &event)
})
}
// EventHandler is the function signature to process the Event.
type EventHandler func(*context.Context, *Event) (interface{}, error)
// Process satisfies EventHandler and processes the Event.
func Process(ctx *context.Context, event *Event) (interface{}, error) {
log.Println("processing event")
// Perform business logic . . .
return nil, nil
}