Skip to content

Commit

Permalink
add post body (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
jfallis authored Jun 3, 2024
1 parent 5476171 commit 7d15394
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
9 changes: 8 additions & 1 deletion http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package g8
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"

Expand Down Expand Up @@ -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 {
Expand Down
31 changes: 30 additions & 1 deletion http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/aws/aws-lambda-go/events"
Expand All @@ -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{
Expand All @@ -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 {
Expand Down

0 comments on commit 7d15394

Please sign in to comment.