First iteration of v1 lambdarouter, full API change
This commit is contained in:
parent
83bb9a2aa1
commit
f65f17158c
|
@ -4,12 +4,12 @@ go:
|
||||||
- 1.x
|
- 1.x
|
||||||
|
|
||||||
before_install:
|
before_install:
|
||||||
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
|
|
||||||
- curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
|
- curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
|
||||||
|
|
||||||
install:
|
install:
|
||||||
|
- dep ensure -v
|
||||||
|
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
|
||||||
- chmod +x ./cc-test-reporter
|
- chmod +x ./cc-test-reporter
|
||||||
- dep ensure
|
|
||||||
|
|
||||||
before_script:
|
before_script:
|
||||||
- ./cc-test-reporter before-build
|
- ./cc-test-reporter before-build
|
||||||
|
|
|
@ -2,68 +2,67 @@
|
||||||
|
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
branch = "master"
|
digest = "1:95fd14230b48a74765db94f7064f0b5617f52739a164f6d41e5b57bec5b3ff9b"
|
||||||
digest = "1:9fd3a6ab34bb103ba228eefd044d3f9aa476237ea95a46d12e8cccd3abf3fea2"
|
|
||||||
name = "github.com/armon/go-radix"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = "UT"
|
|
||||||
revision = "1fca145dffbcaa8fe914309b1ec0cfc67500fe61"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:5580dfd33541011ae489dde24be4db55f1de8eaff11165d469342d95a7c0f790"
|
|
||||||
name = "github.com/aws/aws-lambda-go"
|
name = "github.com/aws/aws-lambda-go"
|
||||||
packages = ["events"]
|
packages = [
|
||||||
|
"events",
|
||||||
|
"lambda",
|
||||||
|
"lambda/handlertrace",
|
||||||
|
"lambda/messages",
|
||||||
|
"lambdacontext",
|
||||||
|
]
|
||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "4d30d0ff60440c2d0480a15747c96ee71c3c53d4"
|
revision = "08d251dc58f204411d79012fd6f1beefb7107fea"
|
||||||
version = "v1.2.0"
|
version = "v1.10.0"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
branch = "master"
|
digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec"
|
||||||
digest = "1:f14d1b50e0075fb00177f12a96dd7addf93d1e2883c25befd17285b779549795"
|
name = "github.com/davecgh/go-spew"
|
||||||
name = "github.com/gopherjs/gopherjs"
|
packages = ["spew"]
|
||||||
packages = ["js"]
|
|
||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "0892b62f0d9fb5857760c3cfca837207185117ee"
|
revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73"
|
||||||
|
version = "v1.1.1"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
digest = "1:1e15f4e455f94aeaedfcf9c75b3e1c449b5acba1551c58446b4b45be507c707b"
|
digest = "1:2be5a35f0c5b35162c41bb24971e5dcf6ce825403296ee435429cdcc4e1e847e"
|
||||||
name = "github.com/jtolds/gls"
|
name = "github.com/hashicorp/go-immutable-radix"
|
||||||
packages = ["."]
|
packages = ["."]
|
||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "77f18212c9c7edc9bd6a33d383a7b545ce62f064"
|
revision = "27df80928bb34bb1b0d6d0e01b9e679902e7a6b5"
|
||||||
version = "v4.2.1"
|
version = "v1.0.0"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
digest = "1:cc1c574c9cb5e99b123888c12b828e2d19224ab6c2244bda34647f230bf33243"
|
digest = "1:67474f760e9ac3799f740db2c489e6423a4cde45520673ec123ac831ad849cb8"
|
||||||
name = "github.com/smartystreets/assertions"
|
name = "github.com/hashicorp/golang-lru"
|
||||||
packages = [
|
packages = ["simplelru"]
|
||||||
".",
|
|
||||||
"internal/go-render/render",
|
|
||||||
"internal/oglematchers",
|
|
||||||
]
|
|
||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "7678a5452ebea5b7090a6b163f844c133f523da2"
|
revision = "7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c"
|
||||||
version = "1.8.3"
|
version = "v0.5.1"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
digest = "1:a3e081e593ee8e3b0a9af6a5dcac964c67a40c4f2034b5345b2ad78d05920728"
|
digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe"
|
||||||
name = "github.com/smartystreets/goconvey"
|
name = "github.com/pmezard/go-difflib"
|
||||||
packages = [
|
packages = ["difflib"]
|
||||||
"convey",
|
|
||||||
"convey/gotest",
|
|
||||||
"convey/reporting",
|
|
||||||
]
|
|
||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "9e8dc3f972df6c8fcc0375ef492c24d0bb204857"
|
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
|
||||||
version = "1.6.3"
|
version = "v1.0.0"
|
||||||
|
|
||||||
|
[[projects]]
|
||||||
|
digest = "1:972c2427413d41a1e06ca4897e8528e5a1622894050e2f527b38ddf0f343f759"
|
||||||
|
name = "github.com/stretchr/testify"
|
||||||
|
packages = ["assert"]
|
||||||
|
pruneopts = "UT"
|
||||||
|
revision = "ffdc059bfe9ce6a4e144ba849dbedead332c6053"
|
||||||
|
version = "v1.3.0"
|
||||||
|
|
||||||
[solve-meta]
|
[solve-meta]
|
||||||
analyzer-name = "dep"
|
analyzer-name = "dep"
|
||||||
analyzer-version = 1
|
analyzer-version = 1
|
||||||
input-imports = [
|
input-imports = [
|
||||||
"github.com/armon/go-radix",
|
|
||||||
"github.com/aws/aws-lambda-go/events",
|
"github.com/aws/aws-lambda-go/events",
|
||||||
"github.com/smartystreets/goconvey/convey",
|
"github.com/aws/aws-lambda-go/lambda",
|
||||||
|
"github.com/hashicorp/go-immutable-radix",
|
||||||
|
"github.com/stretchr/testify/assert",
|
||||||
]
|
]
|
||||||
solver-name = "gps-cdcl"
|
solver-name = "gps-cdcl"
|
||||||
solver-version = 1
|
solver-version = 1
|
||||||
|
|
11
Gopkg.toml
11
Gopkg.toml
|
@ -24,18 +24,9 @@
|
||||||
# go-tests = true
|
# go-tests = true
|
||||||
# unused-packages = true
|
# unused-packages = true
|
||||||
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
branch = "master"
|
|
||||||
name = "github.com/armon/go-radix"
|
|
||||||
|
|
||||||
[[constraint]]
|
[[constraint]]
|
||||||
name = "github.com/aws/aws-lambda-go"
|
name = "github.com/aws/aws-lambda-go"
|
||||||
version = "1.2.0"
|
version = "1.x"
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/smartystreets/goconvey"
|
|
||||||
version = "1.6.3"
|
|
||||||
|
|
||||||
[prune]
|
[prune]
|
||||||
go-tests = true
|
go-tests = true
|
||||||
|
|
26
README.md
26
README.md
|
@ -1,8 +1,28 @@
|
||||||
# lambdarouter
|
# lambdarouter
|
||||||
[](https://godoc.org/github.com/mitchelljfs/lambdarouter)
|
[](https://godoc.org/github.com/mitchell/lambdarouter)
|
||||||
[](https://travis-ci.org/mitchell/lambdarouter)
|
[](https://travis-ci.org/mitchell/lambdarouter)
|
||||||
[](https://codeclimate.com/github/mitchelljfs/lambdarouter/test_coverage)
|
[](https://codeclimate.com/github/mitchelljfs/lambdarouter/test_coverage)
|
||||||
[](https://codeclimate.com/github/mitchelljfs/lambdarouter/maintainability)
|
[](https://codeclimate.com/github/mitchelljfs/lambdarouter/maintainability)
|
||||||
[](https://goreportcard.com/report/github.com/mitchelljfs/lambdarouter)
|
[](https://goreportcard.com/report/github.com/mitchell/lambdarouter)
|
||||||
|
|
||||||
So far this package can create a router and routes whose execution utilizes a middleware context pattern, all in one Golang Lambda function. It has full test coverage, and is currently deployed in numerous services where I am employed. Check out the GoDoc Reference to see how to instantiate a router and create endpoints.
|
This package contains a router capable of routing many AWS Lambda API gateway requests to anything
|
||||||
|
that implements the aws-lambda-go/lambda.Handler interface, all in one Lambda function. It plays
|
||||||
|
especially well with go-kit's awslambda transport package. Get started by reading below and visiting
|
||||||
|
the [GoDoc reference](https://godoc.org/github.com/mitchell/lambdarouter).
|
||||||
|
|
||||||
|
## Initializing a Router
|
||||||
|
```
|
||||||
|
r := lambdarouter.New("prefix/")
|
||||||
|
|
||||||
|
r.Get("hello/{name}", helloHandler)
|
||||||
|
r.Post("hello/server", helloHandler)
|
||||||
|
r.Delete("hello", lambda.NewHandler(func() (events.APIGatewayProxyResponse, error) {
|
||||||
|
return events.APIGatewayProxyResponse{
|
||||||
|
Body: "nothing to delete",
|
||||||
|
}, nil
|
||||||
|
}))
|
||||||
|
|
||||||
|
lambda.StartHandler(r)
|
||||||
|
```
|
||||||
|
|
||||||
|
Check out the `examples/` folder for more fleshed out examples in the proper context.
|
||||||
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
# Serverless directories
|
||||||
|
.serverless
|
||||||
|
|
||||||
|
# golang output binary directory
|
||||||
|
bin
|
|
@ -0,0 +1,10 @@
|
||||||
|
.PHONY: all build clean deploy test
|
||||||
|
|
||||||
|
build:
|
||||||
|
env GOOS=linux go build -ldflags="-s -w" -o ./bin/hello ./main.go
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf ./bin
|
||||||
|
|
||||||
|
deploy: clean build
|
||||||
|
sls deploy --verbose
|
|
@ -0,0 +1,47 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/aws/aws-lambda-go/events"
|
||||||
|
"github.com/aws/aws-lambda-go/lambda"
|
||||||
|
"github.com/mitchell/lambdarouter"
|
||||||
|
)
|
||||||
|
|
||||||
|
var r = lambdarouter.New("hellosrv")
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
r.Post("hello", lambda.NewHandler(func() (events.APIGatewayProxyResponse, error) {
|
||||||
|
return events.APIGatewayProxyResponse{
|
||||||
|
StatusCode: http.StatusCreated,
|
||||||
|
Body: "hello world",
|
||||||
|
}, nil
|
||||||
|
}))
|
||||||
|
|
||||||
|
r.Group("hello", func(r *lambdarouter.Router) {
|
||||||
|
r.Get("{name}", lambda.NewHandler(func(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
|
||||||
|
return events.APIGatewayProxyResponse{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Body: "hello " + req.PathParameters["name"],
|
||||||
|
}, nil
|
||||||
|
}))
|
||||||
|
|
||||||
|
r.Put("french", lambda.NewHandler(func() (events.APIGatewayProxyResponse, error) {
|
||||||
|
return events.APIGatewayProxyResponse{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Body: "bonjour le monde",
|
||||||
|
}, nil
|
||||||
|
}))
|
||||||
|
|
||||||
|
r.Get("french/{prenom}", lambda.NewHandler(func(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
|
||||||
|
return events.APIGatewayProxyResponse{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Body: "bonjour " + req.PathParameters["prenom"],
|
||||||
|
}, nil
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
lambda.StartHandler(r)
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
service: lambdarouter-hello-world
|
||||||
|
frameworkVersion: ">=1.28.0 <2.0.0"
|
||||||
|
|
||||||
|
provider:
|
||||||
|
name: aws
|
||||||
|
runtime: go1.x
|
||||||
|
stage: ${opt:stage, 'dev'}
|
||||||
|
region: us-west-2
|
||||||
|
# iamRoleStatements:
|
||||||
|
# environment:
|
||||||
|
|
||||||
|
package:
|
||||||
|
exclude:
|
||||||
|
- ./**
|
||||||
|
include:
|
||||||
|
- ./bin/**
|
||||||
|
|
||||||
|
functions:
|
||||||
|
hello:
|
||||||
|
handler: bin/hello
|
||||||
|
events:
|
||||||
|
- http:
|
||||||
|
path: hellosrv/hello
|
||||||
|
method: post
|
||||||
|
- http:
|
||||||
|
path: hellosrv/hello/{name}
|
||||||
|
method: get
|
||||||
|
request:
|
||||||
|
parameters:
|
||||||
|
path:
|
||||||
|
name: true
|
||||||
|
- http:
|
||||||
|
path: hellosrv/hello/french
|
||||||
|
method: put
|
||||||
|
- http:
|
||||||
|
path: hellosrv/hello/french/{prenom}
|
||||||
|
method: get
|
||||||
|
request:
|
||||||
|
parameters:
|
||||||
|
path:
|
||||||
|
prenom: true
|
||||||
|
#resources:
|
|
@ -0,0 +1,9 @@
|
||||||
|
module github.com/mitchell/lambdarouter
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/aws/aws-lambda-go v1.10.0
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/hashicorp/go-immutable-radix v1.0.0
|
||||||
|
github.com/hashicorp/golang-lru v0.5.1 // indirect
|
||||||
|
github.com/stretchr/testify v1.3.0
|
||||||
|
)
|
|
@ -0,0 +1,17 @@
|
||||||
|
github.com/aws/aws-lambda-go v1.10.0 h1:uafgdfYGQD0UeT7d2uKdyWW8j/ZYRifRPIdmeqLzLCk=
|
||||||
|
github.com/aws/aws-lambda-go v1.10.0/go.mod h1:zUsUQhAUjYzR8AuduJPCfhBuKWUaDbQiPOG+ouzmE1A=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0=
|
||||||
|
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM=
|
||||||
|
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||||
|
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||||
|
github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU=
|
||||||
|
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
243
router.go
243
router.go
|
@ -3,207 +3,134 @@ package lambdarouter
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"log"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
radix "github.com/armon/go-radix"
|
|
||||||
"github.com/aws/aws-lambda-go/events"
|
"github.com/aws/aws-lambda-go/events"
|
||||||
|
"github.com/aws/aws-lambda-go/lambda"
|
||||||
|
iradix "github.com/hashicorp/go-immutable-radix"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
// Router holds the defined routes for use upon invocation.
|
||||||
post = http.MethodPost
|
type Router struct {
|
||||||
get = http.MethodGet
|
events *iradix.Tree
|
||||||
put = http.MethodPut
|
|
||||||
patch = http.MethodPatch
|
|
||||||
delete = http.MethodDelete
|
|
||||||
)
|
|
||||||
|
|
||||||
// APIGContext is used as the input and output of handler functions.
|
|
||||||
// The Body, Claims, Path, and QryStr will be populated by the the APIGatewayProxyRequest.
|
|
||||||
// The Request itself is also passed through if you need further access.
|
|
||||||
// Fill the Status and Body, or Status and Error to respond.
|
|
||||||
type APIGContext struct {
|
|
||||||
Claims map[string]interface{}
|
|
||||||
Context context.Context
|
|
||||||
Path map[string]string
|
|
||||||
QryStr map[string]string
|
|
||||||
Request *events.APIGatewayProxyRequest
|
|
||||||
Status int
|
|
||||||
Body []byte
|
|
||||||
Err error
|
|
||||||
}
|
|
||||||
|
|
||||||
// APIGHandler is the interface a handler function must implement to be used
|
|
||||||
// with Get, Post, Put, Patch, and Delete.
|
|
||||||
type APIGHandler func(ctx *APIGContext)
|
|
||||||
|
|
||||||
// APIGRouter is the object that handlers build upon and is used in the end to respond.
|
|
||||||
type APIGRouter struct {
|
|
||||||
request *events.APIGatewayProxyRequest
|
|
||||||
endpoints map[string]*radix.Tree
|
|
||||||
params map[string]interface{}
|
|
||||||
prefix string
|
prefix string
|
||||||
headers map[string]string
|
|
||||||
context context.Context
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// APIGRouterConfig is used as the input to NewAPIGRouter, request is your incoming
|
// New initializes an empty router.
|
||||||
// apig request and prefix will be stripped of all incoming request paths. Headers
|
func New(prefix string) Router {
|
||||||
// will be sent with all responses.
|
if prefix[0] != '/' {
|
||||||
type APIGRouterConfig struct {
|
prefix = "/" + prefix
|
||||||
Context context.Context
|
}
|
||||||
Request *events.APIGatewayProxyRequest
|
if prefix[len(prefix)-1] != '/' {
|
||||||
Prefix string
|
prefix += "/"
|
||||||
Headers map[string]string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NOTE: Begin router methods.
|
return Router{
|
||||||
|
events: iradix.New(),
|
||||||
// NewAPIGRouter creates a new router using the given router config.
|
prefix: prefix,
|
||||||
func NewAPIGRouter(cfg *APIGRouterConfig) *APIGRouter {
|
|
||||||
return &APIGRouter{
|
|
||||||
request: cfg.Request,
|
|
||||||
endpoints: map[string]*radix.Tree{
|
|
||||||
post: radix.New(),
|
|
||||||
get: radix.New(),
|
|
||||||
put: radix.New(),
|
|
||||||
patch: radix.New(),
|
|
||||||
delete: radix.New(),
|
|
||||||
},
|
|
||||||
params: map[string]interface{}{},
|
|
||||||
prefix: cfg.Prefix,
|
|
||||||
headers: cfg.Headers,
|
|
||||||
context: cfg.Context,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get creates a new get endpoint.
|
// Get adds a new GET method route to the router. The path parameter is the route path you wish to
|
||||||
func (r *APIGRouter) Get(route string, handlers ...APIGHandler) {
|
// define. The handler parameter is a lambda.Handler to invoke if an incoming path matches the
|
||||||
r.addEndpoint(get, route, handlers)
|
// route.
|
||||||
|
func (r *Router) Get(path string, handler lambda.Handler) {
|
||||||
|
path = r.prefix + path
|
||||||
|
r.addEvent(http.MethodGet+path, event{h: handler})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post creates a new post endpoint.
|
// Post adds a new POST method route to the router. The path parameter is the route path you wish to
|
||||||
func (r *APIGRouter) Post(route string, handlers ...APIGHandler) {
|
// define. The handler parameter is a lambda.Handler to invoke if an incoming path matches the
|
||||||
r.addEndpoint(post, route, handlers)
|
// route.
|
||||||
|
func (r *Router) Post(path string, handler lambda.Handler) {
|
||||||
|
path = r.prefix + path
|
||||||
|
r.addEvent(http.MethodPost+path, event{h: handler})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put creates a new put endpoint.
|
// Put adds a new PUT method route to the router. The path parameter is the route path you wish to
|
||||||
func (r *APIGRouter) Put(route string, handlers ...APIGHandler) {
|
// define. The handler parameter is a lambda.Handler to invoke if an incoming path matches the
|
||||||
r.addEndpoint(put, route, handlers)
|
// route.
|
||||||
|
func (r *Router) Put(path string, handler lambda.Handler) {
|
||||||
|
path = r.prefix + path
|
||||||
|
r.addEvent(http.MethodPut+path, event{h: handler})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Patch creates a new patch endpoint
|
// Patch adds a new PATCH method route to the router. The path parameter is the route path you wish
|
||||||
func (r *APIGRouter) Patch(route string, handlers ...APIGHandler) {
|
// to define. The handler parameter is a lambda.Handler to invoke if an incoming path matches the
|
||||||
r.addEndpoint(patch, route, handlers)
|
// route.
|
||||||
|
func (r *Router) Patch(path string, handler lambda.Handler) {
|
||||||
|
path = r.prefix + path
|
||||||
|
r.addEvent(http.MethodPatch+path, event{h: handler})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete creates a new delete endpoint.
|
// Delete adds a new DELETE method route to the router. The path parameter is the route path you
|
||||||
func (r *APIGRouter) Delete(route string, handlers ...APIGHandler) {
|
// wish to define. The handler parameter is a lambda.Handler to invoke if an incoming path matches
|
||||||
r.addEndpoint(delete, route, handlers)
|
// the route.
|
||||||
|
func (r *Router) Delete(path string, handler lambda.Handler) {
|
||||||
|
path = r.prefix + path
|
||||||
|
r.addEvent(http.MethodDelete+path, event{h: handler})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Respond returns an APIGatewayProxyResponse to respond to the lambda request.
|
// Invoke implements the lambda.Handler interface for the Router type.
|
||||||
func (r *APIGRouter) Respond() events.APIGatewayProxyResponse {
|
func (r Router) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
|
||||||
var (
|
var req events.APIGatewayProxyRequest
|
||||||
handlersInterface interface{}
|
|
||||||
ok bool
|
|
||||||
status int
|
|
||||||
respbody []byte
|
|
||||||
err error
|
|
||||||
|
|
||||||
endpointTree = r.endpoints[r.request.HTTPMethod]
|
if err := json.Unmarshal(payload, &req); err != nil {
|
||||||
path = strings.TrimPrefix(r.request.Path, r.prefix)
|
return nil, err
|
||||||
inPath = path
|
|
||||||
response = events.APIGatewayProxyResponse{}
|
|
||||||
splitPath = stripSlashesAndSplit(path)
|
|
||||||
)
|
|
||||||
|
|
||||||
for p := range r.params {
|
|
||||||
if r.request.PathParameters[p] != "" {
|
|
||||||
pval := r.request.PathParameters[p]
|
|
||||||
for i, v := range splitPath {
|
|
||||||
if v == pval {
|
|
||||||
splitPath[i] = "{" + p + "}"
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
path = "/" + strings.Join(splitPath, "/")
|
|
||||||
|
|
||||||
if handlersInterface, ok = endpointTree.Get(path); !ok {
|
|
||||||
respbody, _ = json.Marshal(map[string]string{"error": "no route matching path found"})
|
|
||||||
|
|
||||||
response.StatusCode = http.StatusNotFound
|
|
||||||
response.Body = string(respbody)
|
|
||||||
response.Headers = r.headers
|
|
||||||
return response
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handlers := handlersInterface.([]APIGHandler)
|
path := req.Path
|
||||||
|
|
||||||
for _, handler := range handlers {
|
for param, value := range req.PathParameters {
|
||||||
ctx := &APIGContext{
|
path = strings.Replace(path, value, "{"+param+"}", -1)
|
||||||
Body: []byte(r.request.Body),
|
|
||||||
Path: r.request.PathParameters,
|
|
||||||
QryStr: r.request.QueryStringParameters,
|
|
||||||
Request: r.request,
|
|
||||||
Context: r.context,
|
|
||||||
}
|
|
||||||
if r.request.RequestContext.Authorizer["claims"] != nil {
|
|
||||||
ctx.Claims = r.request.RequestContext.Authorizer["claims"].(map[string]interface{})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handler(ctx)
|
i, found := r.events.Get([]byte(req.HTTPMethod + path))
|
||||||
status, respbody, err = ctx.respDeconstruct()
|
|
||||||
|
|
||||||
if err != nil {
|
if !found {
|
||||||
respbody, _ = json.Marshal(map[string]string{"error": err.Error()})
|
return json.Marshal(events.APIGatewayProxyResponse{
|
||||||
if strings.Contains(err.Error(), "record not found") {
|
StatusCode: http.StatusNotFound,
|
||||||
status = 204
|
Body: "not found",
|
||||||
} else if status != 204 && status < 400 {
|
})
|
||||||
status = 400
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("%v %v %v error: %v \n", r.request.HTTPMethod, inPath, status, err.Error())
|
e := i.(event)
|
||||||
log.Println("error causing body: " + r.request.Body)
|
return e.h.Invoke(ctx, payload)
|
||||||
response.StatusCode = status
|
|
||||||
response.Body = string(respbody)
|
|
||||||
response.Headers = r.headers
|
|
||||||
return response
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
response.StatusCode = status
|
// Group allows you to define many routes with the same prefix. The prefix parameter will apply the
|
||||||
response.Body = string(respbody)
|
// prefix to all routes defined in the function. The fn parmater is a function in which the grouped
|
||||||
response.Headers = r.headers
|
// routes should be defined.
|
||||||
return response
|
func (r *Router) Group(prefix string, fn func(r *Router)) {
|
||||||
|
if prefix[0] == '/' {
|
||||||
|
prefix = prefix[1:]
|
||||||
|
}
|
||||||
|
if prefix[len(prefix)-1] != '/' {
|
||||||
|
prefix += "/"
|
||||||
}
|
}
|
||||||
|
|
||||||
// NOTE: Begin helper functions.
|
original := r.prefix
|
||||||
func stripSlashesAndSplit(s string) []string {
|
r.prefix += prefix
|
||||||
s = strings.TrimPrefix(s, "/")
|
fn(r)
|
||||||
s = strings.TrimSuffix(s, "/")
|
r.prefix = original
|
||||||
return strings.Split(s, "/")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ctx *APIGContext) respDeconstruct() (int, []byte, error) {
|
type event struct {
|
||||||
return ctx.Status, ctx.Body, ctx.Err
|
h lambda.Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *APIGRouter) addEndpoint(method string, route string, handlers []APIGHandler) {
|
func (r *Router) addEvent(key string, e event) {
|
||||||
if _, overwrite := r.endpoints[method].Insert(route, handlers); overwrite {
|
if r.events == nil {
|
||||||
panic("endpoint already existent")
|
panic("router not initialized")
|
||||||
}
|
}
|
||||||
|
|
||||||
rtearr := stripSlashesAndSplit(route)
|
routes, _, overwrite := r.events.Insert([]byte(key), e)
|
||||||
for _, v := range rtearr {
|
|
||||||
if strings.HasPrefix(v, "{") {
|
if overwrite {
|
||||||
v = strings.TrimPrefix(v, "{")
|
panic(fmt.Sprintf("event '%s' already exists", key))
|
||||||
v = strings.TrimSuffix(v, "}")
|
|
||||||
r.params[v] = nil // adding params as *unique* keys
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
r.events = routes
|
||||||
}
|
}
|
||||||
|
|
221
router_test.go
221
router_test.go
|
@ -1,184 +1,101 @@
|
||||||
package lambdarouter
|
package lambdarouter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/aws/aws-lambda-go/events"
|
"github.com/aws/aws-lambda-go/events"
|
||||||
. "github.com/smartystreets/goconvey/convey"
|
"github.com/aws/aws-lambda-go/lambda"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRouterSpec(t *testing.T) {
|
func TestRouter(t *testing.T) {
|
||||||
|
a := assert.New(t)
|
||||||
|
|
||||||
Convey("Given an instantiated router", t, func() {
|
desc(t, 0, "Intialize Router and")
|
||||||
request := events.APIGatewayProxyRequest{}
|
r := New("prefix")
|
||||||
rtr := NewAPIGRouter(&APIGRouterConfig{
|
handler := lambda.NewHandler(handler)
|
||||||
Request: &request,
|
ctx := context.Background()
|
||||||
Prefix: "/shipping",
|
|
||||||
Headers: map[string]string{
|
desc(t, 2, "Get|Post|Put|Patch|Delete method should")
|
||||||
"Access-Control-Allow-Origin": "*",
|
{
|
||||||
"Access-Control-Allow-Credentials": "true",
|
desc(t, 4, "insert a new route succesfully")
|
||||||
},
|
a.NotPanics(func() {
|
||||||
|
r.Get("thing/{id}", handler)
|
||||||
|
r.Delete("thing/{id}", handler)
|
||||||
|
r.Put("thing", handler)
|
||||||
})
|
})
|
||||||
|
|
||||||
Convey("When the handler func does NOT return an error", func() {
|
desc(t, 4, "panic when inserting the same route")
|
||||||
hdlrfunc := func(ctx *APIGContext) {
|
a.Panics(func() {
|
||||||
ctx.Status = http.StatusOK
|
r.Put("thing", handler)
|
||||||
ctx.Body = []byte("hello")
|
})
|
||||||
ctx.Err = nil
|
|
||||||
|
desc(t, 4, "panic when router is uninitalized")
|
||||||
|
var r2 Router
|
||||||
|
a.Panics(func() {
|
||||||
|
r2.Patch("panic", handler)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
Convey("And a Get handler expecting the pattern /listings/{id}/state/{event} is defined", func() {
|
desc(t, 2, "PrefixGroup method should")
|
||||||
rtr.Get("/listings/{id}/state/{event}", hdlrfunc)
|
{
|
||||||
rtr.Post("/orders", func(ctx *APIGContext) {})
|
desc(t, 4, "insert routes with the specified prefix succesfully")
|
||||||
rtr.Put("/orders", func(ctx *APIGContext) {})
|
r.Group("/ding", func(r *Router) {
|
||||||
rtr.Patch("/orders", func(ctx *APIGContext) {})
|
r.Post("dong/{door}", handler)
|
||||||
rtr.Delete("/orders/{id}", func(ctx *APIGContext) {})
|
})
|
||||||
|
|
||||||
Convey("And the request matches the pattern and the path params are filled", func() {
|
|
||||||
request.HTTPMethod = http.MethodGet
|
|
||||||
request.Path = "/shipping/listings/57/state/list"
|
|
||||||
request.PathParameters = map[string]string{
|
|
||||||
"id": "57",
|
|
||||||
"event": "list",
|
|
||||||
}
|
|
||||||
request.RequestContext.Authorizer = map[string]interface{}{
|
|
||||||
"claims": map[string]interface{}{
|
|
||||||
"cognito:username": "mitchell",
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Convey("The router will return the expected status, body, and headers", func() {
|
desc(t, 2, "Invoke method should")
|
||||||
response := rtr.Respond()
|
{
|
||||||
|
e := events.APIGatewayProxyRequest{
|
||||||
|
Path: "/prefix/ding/dong/mitchell",
|
||||||
|
HTTPMethod: http.MethodPost,
|
||||||
|
PathParameters: map[string]string{"door": "mitchell"},
|
||||||
|
}
|
||||||
|
|
||||||
So(response.StatusCode, ShouldEqual, http.StatusOK)
|
desc(t, 4, "should succesfully route and invoke a defined route")
|
||||||
So(response.Body, ShouldEqual, "hello")
|
ejson, _ := json.Marshal(e)
|
||||||
So(response.Headers, ShouldResemble, map[string]string{
|
|
||||||
"Access-Control-Allow-Origin": "*",
|
|
||||||
"Access-Control-Allow-Credentials": "true",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
Convey("And the request does NOT match the pattern", func() {
|
res, err := r.Invoke(ctx, ejson)
|
||||||
request.HTTPMethod = http.MethodGet
|
|
||||||
request.Path = "/orders/filter"
|
|
||||||
|
|
||||||
Convey("The router will return an error body and a status not found", func() {
|
a.NoError(err)
|
||||||
response := rtr.Respond()
|
a.Exactly("null", string(res))
|
||||||
|
|
||||||
So(response.StatusCode, ShouldEqual, http.StatusNotFound)
|
desc(t, 4, "return the expected response when a route is not found")
|
||||||
So(response.Body, ShouldEqual, "{\"error\":\"no route matching path found\"}")
|
e.Path = "thing"
|
||||||
So(response.Headers, ShouldResemble, map[string]string{
|
e.PathParameters = nil
|
||||||
"Access-Control-Allow-Origin": "*",
|
ejson2, _ := json.Marshal(e)
|
||||||
"Access-Control-Allow-Credentials": "true",
|
eres := events.APIGatewayProxyResponse{
|
||||||
})
|
StatusCode: http.StatusNotFound,
|
||||||
})
|
Body: "not found",
|
||||||
})
|
}
|
||||||
|
eresjson, _ := json.Marshal(eres)
|
||||||
|
|
||||||
Convey("And a Get handler expecting the pattern /listings/{id}/state/{event} is defined AGAIN", func() {
|
res, err = r.Invoke(ctx, ejson2)
|
||||||
So(func() {
|
|
||||||
rtr.Get("/listings/{id}/state/{event}", hdlrfunc)
|
|
||||||
}, ShouldPanicWith, "endpoint already existent")
|
|
||||||
})
|
|
||||||
|
|
||||||
Convey("And a Get handler expecting the pattern /orders/filter", func() {
|
a.NoError(err)
|
||||||
rtr.Get("/orders/filter", hdlrfunc)
|
a.ElementsMatch(eresjson, res)
|
||||||
|
|
||||||
Convey("And the request matches the pattern and the path params are filled", func() {
|
desc(t, 4, "return an error when the there is an issue with the incoming event")
|
||||||
request.HTTPMethod = http.MethodGet
|
_, err = r.Invoke(ctx, nil)
|
||||||
request.Path = "/shipping/orders/filter"
|
|
||||||
|
|
||||||
Convey("The router will return the expected status and body", func() {
|
a.Error(err)
|
||||||
response := rtr.Respond()
|
}
|
||||||
|
|
||||||
So(response.StatusCode, ShouldEqual, http.StatusOK)
|
|
||||||
So(response.Body, ShouldEqual, "hello")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
Convey("And the request does NOT match either of the patterns", func() {
|
|
||||||
request.HTTPMethod = http.MethodGet
|
|
||||||
request.Path = "/shipping/orders/filter/by_user"
|
|
||||||
|
|
||||||
Convey("The router will return an error body and a status not found", func() {
|
|
||||||
response := rtr.Respond()
|
|
||||||
|
|
||||||
So(response.StatusCode, ShouldEqual, http.StatusNotFound)
|
|
||||||
So(response.Body, ShouldEqual, "{\"error\":\"no route matching path found\"}")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
})
|
|
||||||
|
|
||||||
Convey("When the handler func does return a record not found", func() {
|
|
||||||
hdlrfunc := func(ctx *APIGContext) {
|
|
||||||
ctx.Status = http.StatusNoContent
|
|
||||||
ctx.Body = []byte("hello")
|
|
||||||
ctx.Err = errors.New("record not found")
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Convey("And a Get handler expecting the pattern /listings/{id}/state/{event} is defined", func() {
|
func handler() error {
|
||||||
rtr.Get("/listings/{id}/state/{event}", hdlrfunc)
|
return nil
|
||||||
|
|
||||||
Convey("And the request matches the pattern and the path params are filled", func() {
|
|
||||||
request.HTTPMethod = http.MethodGet
|
|
||||||
request.Path = "/shipping/listings/57/state/list"
|
|
||||||
request.PathParameters = map[string]string{
|
|
||||||
"id": "57",
|
|
||||||
"event": "list",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Convey("The router will return the expected status and body", func() {
|
func desc(t *testing.T, depth int, str string, args ...interface{}) {
|
||||||
response := rtr.Respond()
|
for i := 0; i < depth; i++ {
|
||||||
|
str = " " + str
|
||||||
So(response.StatusCode, ShouldEqual, http.StatusNoContent)
|
|
||||||
So(response.Body, ShouldEqual, "{\"error\":\"record not found\"}")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
Convey("When the handler func does return a status < 400", func() {
|
|
||||||
middlefunc1 := func(ctx *APIGContext) {
|
|
||||||
ctx.Status = http.StatusOK
|
|
||||||
ctx.Body = []byte("hello")
|
|
||||||
ctx.Err = nil
|
|
||||||
}
|
|
||||||
middlefunc2 := func(ctx *APIGContext) {
|
|
||||||
ctx.Status = http.StatusOK
|
|
||||||
ctx.Body = []byte("hello")
|
|
||||||
ctx.Err = errors.New("bad request")
|
|
||||||
}
|
|
||||||
hdlrfunc := func(ctx *APIGContext) {
|
|
||||||
ctx.Status = http.StatusOK
|
|
||||||
ctx.Body = []byte("hello")
|
|
||||||
ctx.Err = nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Convey("And a Get handler expecting the pattern /listings/{id}/state/{event} is defined", func() {
|
t.Log(fmt.Sprintf(str, args...))
|
||||||
rtr.Get("/listings/{id}/state/{event}", middlefunc1, middlefunc2, hdlrfunc)
|
|
||||||
|
|
||||||
Convey("And the request matches the pattern and the path params are filled", func() {
|
|
||||||
request.HTTPMethod = http.MethodGet
|
|
||||||
request.Path = "/shipping/listings/57/state/list"
|
|
||||||
request.PathParameters = map[string]string{
|
|
||||||
"id": "57",
|
|
||||||
"event": "list",
|
|
||||||
}
|
|
||||||
|
|
||||||
Convey("The router will return the expected status and body", func() {
|
|
||||||
response := rtr.Respond()
|
|
||||||
|
|
||||||
So(response.StatusCode, ShouldEqual, http.StatusBadRequest)
|
|
||||||
So(response.Body, ShouldEqual, "{\"error\":\"bad request\"}")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue