Skip to content

iamatypeofwalrus/shim

Repository files navigation

Build 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 Go modules to model its dependencies.

Example

For an extensive example on how shim fits in with other AWS serverless tooling like SAM Local and the Serverless Application Model (SAM) specification head over to the this example in the wiki

Note: API Gateway

Make sure that proxy pass integration in API Gateway is enabled to make sure your application receives every request sent to your API Gateway endpoint.

Code

With Rest API (API Gateway Proxy Request, Response)

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.HandleRestApiRequests(mux)

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

With HTTP API (API Gateway V2 Request, Response)

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.HandleHttpApiRequests(mux)

  // Pass your router to shim and let Lambda handle the rest
  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 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)
  )

  ...
}

There is also a shim for the slog package

func main() {
  ...

  // Debug with Slog calls the Debug method on slog. Slog defaults to INFO, so it needs to be set to Debug so you can see the messages
  logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
  shim := shim.New(
    nil, // or your mux
    shim.SetDebugWithSlog(l)
  )

  ...
}