From 7d15394e7df465d5c2834afad1860e360a56583a Mon Sep 17 00:00:00 2001 From: John Fallis <21218504+jfallis@users.noreply.github.com> Date: Mon, 3 Jun 2024 16:38:45 +0100 Subject: [PATCH] add post body (#20) --- http.go | 9 ++++++++- http_test.go | 31 ++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/http.go b/http.go index cb6fc4d..e8ffa0e 100644 --- a/http.go +++ b/http.go @@ -3,6 +3,7 @@ package g8 import ( "encoding/json" "fmt" + "io" "net/http" "strings" @@ -43,8 +44,14 @@ func LambdaAdapter(l LambdaHandler) func(http.ResponseWriter, *http.Request) { switch eventHandler := l.Handler.(type) { case func(ctx *APIGatewayProxyContext) error: fmt.Printf("%s %s \n", r.Method, r.URL.Path) + + buf := new(strings.Builder) + if _, err := io.Copy(buf, r.Body); err != nil { + panic(err) + } + ctx := &APIGatewayProxyContext{ - Request: adapter.APIGatewayProxyRequestAdaptor(r, "", l.PathPattern, nil, nil), + Request: adapter.APIGatewayProxyRequestAdaptor(r, buf.String(), l.PathPattern, nil, nil), } if eErr := eventHandler(ctx); eErr != nil { diff --git a/http_test.go b/http_test.go index 576de53..965a791 100644 --- a/http_test.go +++ b/http_test.go @@ -4,6 +4,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "strings" "testing" "github.com/aws/aws-lambda-go/events" @@ -12,7 +13,7 @@ import ( "github.com/JSainsburyPLC/g8" ) -func TestLambdaAdapter(t *testing.T) { +func TestLambdaAdapterGetMethod(t *testing.T) { l := g8.LambdaHandler{ Handler: func(ctx *g8.APIGatewayProxyContext) error { ctx.Response = events.APIGatewayProxyResponse{ @@ -38,6 +39,34 @@ func TestLambdaAdapter(t *testing.T) { assert.Equal(t, "success", w.Body.String()) } +func TestLambdaAdapterPostMethod(t *testing.T) { + l := g8.LambdaHandler{ + Handler: func(ctx *g8.APIGatewayProxyContext) error { + ctx.Response = events.APIGatewayProxyResponse{ + StatusCode: http.StatusOK, + Headers: map[string]string{"Content-Type": "text/plain"}, + MultiValueHeaders: map[string][]string{"Set-Cookie": {"cookie1", "cookie2"}}, + Body: "success", + } + return nil + }, + Method: http.MethodPost, + PathPattern: "/test/url/path/{var1}/{var2}", + } + + reqBody := strings.NewReader(`{"key":"value"}`) + + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/test/url/path/value1/value2", reqBody) + r.Header.Set("Content-Type", "text/plain") + g8.LambdaAdapter(l)(w, r) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "text/plain", w.Header().Get("Content-Type")) + assert.Equal(t, "cookie1,cookie2", w.Header().Get("Set-Cookie")) + assert.Equal(t, "success", w.Body.String()) +} + func TestLambdaAdapter_without_content_type(t *testing.T) { l := g8.LambdaHandler{ Handler: func(ctx *g8.APIGatewayProxyContext) error {