33package lambda
44
55import (
6+ "context"
67 "log"
78 "net"
89 "net/rpc"
@@ -37,8 +38,12 @@ import (
3738// Where "TIn" and "TOut" are types compatible with the "encoding/json" standard library.
3839// See https://golang.org/pkg/encoding/json/#Unmarshal for how deserialization behaves
3940func 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 ))
4247}
4348
4449// StartHandler takes in a Handler wrapper interface which can be implemented either by a
@@ -48,15 +53,26 @@ func Start(handler interface{}) {
4853//
4954// func Invoke(context.Context, []byte) ([]byte, error)
5055func 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 ) {
5165 port := os .Getenv ("_LAMBDA_SERVER_PORT" )
5266 lis , err := net .Listen ("tcp" , "localhost:" + port )
5367 if err != nil {
5468 log .Fatal (err )
5569 }
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 {
5873 log .Fatal ("failed to register handler function" )
5974 }
75+
6076 rpc .Accept (lis )
6177 log .Fatal ("accept should not have returned" )
6278}
0 commit comments