3
3
package lambda
4
4
5
5
import (
6
+ "context"
6
7
"log"
7
8
"net"
8
9
"net/rpc"
@@ -37,8 +38,12 @@ import (
37
38
// Where "TIn" and "TOut" are types compatible with the "encoding/json" standard library.
38
39
// See https://golang.org/pkg/encoding/json/#Unmarshal for how deserialization behaves
39
40
func Start (handler interface {}) {
40
- wrappedHandler := NewHandler (handler )
41
- StartHandler (wrappedHandler )
41
+ StartWithContext (context .Background (), handler )
42
+ }
43
+
44
+ // StartWithContext is the same as Start except sets the base context for the function.
45
+ func StartWithContext (ctx context.Context , handler interface {}) {
46
+ StartHandlerWithContext (ctx , NewHandler (handler ))
42
47
}
43
48
44
49
// StartHandler takes in a Handler wrapper interface which can be implemented either by a
@@ -48,15 +53,26 @@ func Start(handler interface{}) {
48
53
//
49
54
// func Invoke(context.Context, []byte) ([]byte, error)
50
55
func StartHandler (handler Handler ) {
56
+ StartHandlerWithContext (context .Background (), handler )
57
+ }
58
+
59
+ // StartHandlerWithContext is the same as StartHandler except sets the base context for the function.
60
+ //
61
+ // Handler implementation requires a single "Invoke()" function:
62
+ //
63
+ // func Invoke(context.Context, []byte) ([]byte, error)
64
+ func StartHandlerWithContext (ctx context.Context , handler Handler ) {
51
65
port := os .Getenv ("_LAMBDA_SERVER_PORT" )
52
66
lis , err := net .Listen ("tcp" , "localhost:" + port )
53
67
if err != nil {
54
68
log .Fatal (err )
55
69
}
56
- err = rpc .Register (NewFunction (handler ))
57
- if err != nil {
70
+
71
+ fn := NewFunction (handler ).withContext (ctx )
72
+ if err := rpc .Register (fn ); err != nil {
58
73
log .Fatal ("failed to register handler function" )
59
74
}
75
+
60
76
rpc .Accept (lis )
61
77
log .Fatal ("accept should not have returned" )
62
78
}
0 commit comments