Skip to content

iamatypeofwalrus/shim

Repository files navigation

AWS CodeBuild Status GoDoc Go Report Card

Shim

Shim is a thin layer between API Gateway integration requests via Lambda and the standard library http.Handler interface. It allows you to write plain ol' Go and run it on Lambda with minimal modifications. Bring your own router!

Shim uses dep to manage its dependencies. You can add shim to your dep project by running:

dep ensure -add github.com/iamatypeofwalrus/shim

Usage

CloudFormation

You'll want to use the proxy pass integration with API Gateway to make sure your application receives every request sent to your API Gateway endpoint.

# Here we're using the SAM specification to define our function
#
# Note: You need both the Root AND the Greedy event in order to capture all
#       events sent to your web app.
YourFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: main
    Runtime: go1.x
    Role: ...
    Events:
      ProxyApiRoot:
        Type: Api
        Properties:
          Path: /
          Method: ANY
      ProxyApiGreedy:
        Type: Api
        Properties:
          Path: /{proxy+}
          Method: ANY

Go Code

With your own router

package main

import (
  "fmt"
  "net/http"

  "github.com/aws/aws-lambda-go/lambda"

  "github.com/iamatypeofwalrus/shim"
)

func main() {
  // Create a router as normal. Any router that satisfies the http.Handler interface
  // is accepted!
  mux := http.NewServeMux()
  mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    fmt.Fprint(w, "hello, world")
  })

  s := shim.New(mux)

  // Pass your router to shim and let Lambda handle the rest
  lambda.Start(s.Handle)
}

With the default router

package main

import (
  "fmt"
  "net/http"

  "github.com/aws/aws-lambda-go/lambda"

  "github.com/iamatypeofwalrus/shim"
)

func main() {
  // Shim works with the http.DefaultServeMux. Create routes and handlers against the router normal.
  http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    fmt.Fprint(w, "hello, world")
  })

  // Simply pass nil to shim to use the http.DefaultServeMux
  s := shim.New(nil)

  lambda.Start(s.Handle)
}

With Debugging Logger

You can pull logs from various steps in the shim by passing the SetDebugLogger option. It accepts any logger that provides the Println and Printf functions a lá the standard library logger.

func main() {
  ...

  l := log.New(os.Stdout, "", log.LstdFlags)
  shim := shim.New(
    nil, // or your mux
    shim.SetDebugLogger(l)
  )

  lambda.Start(shim.Handle)
}

About

HTTP Handler shim for Go projects running on AWS Lambda

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages