entry.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. package lambda
  3. import (
  4. "log"
  5. "net"
  6. "net/rpc"
  7. "os"
  8. )
  9. // Start takes a handler and talks to an internal Lambda endpoint to pass requests to the handler. If the
  10. // handler does not match one of the supported types an appropriate error message will be returned to the caller.
  11. // Start blocks, and does not return after being called.
  12. //
  13. // Rules:
  14. //
  15. // * handler must be a function
  16. // * handler may take between 0 and two arguments.
  17. // * if there are two arguments, the first argument must satisfy the "context.Context" interface.
  18. // * handler may return between 0 and two arguments.
  19. // * if there are two return values, the second argument must be an error.
  20. // * if there is one return value it must be an error.
  21. //
  22. // Valid function signatures:
  23. //
  24. // func ()
  25. // func () error
  26. // func (TIn) error
  27. // func () (TOut, error)
  28. // func (TIn) (TOut, error)
  29. // func (context.Context) error
  30. // func (context.Context, TIn) error
  31. // func (context.Context) (TOut, error)
  32. // func (context.Context, TIn) (TOut, error)
  33. //
  34. // Where "TIn" and "TOut" are types compatible with the "encoding/json" standard library.
  35. // See https://golang.org/pkg/encoding/json/#Unmarshal for how deserialization behaves
  36. func Start(handler interface{}) {
  37. wrappedHandler := NewHandler(handler)
  38. StartHandler(wrappedHandler)
  39. }
  40. // StartHandler takes in a Handler wrapper interface which can be implemented either by a
  41. // custom function or a struct.
  42. //
  43. // Handler implementation requires a single "Invoke()" function:
  44. //
  45. // func Invoke(context.Context, []byte) ([]byte, error)
  46. func StartHandler(handler Handler) {
  47. port := os.Getenv("_LAMBDA_SERVER_PORT")
  48. lis, err := net.Listen("tcp", "localhost:"+port)
  49. if err != nil {
  50. log.Fatal(err)
  51. }
  52. function := new(Function)
  53. function.handler = handler
  54. err = rpc.Register(function)
  55. if err != nil {
  56. log.Fatal("failed to register handler function")
  57. }
  58. rpc.Accept(lis)
  59. log.Fatal("accept should not have returned")
  60. }