Skip to content

Commit 4190fa3

Browse files
authored
Add GetEndpoint test case for EndpointFunc and fix empty request handling (#66)
1 parent 6ce2a14 commit 4190fa3

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

xapi/endpoint.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package xapi
33
import (
44
"context"
55
"encoding/json"
6+
"io"
67
"net/http"
78
)
89

@@ -69,13 +70,18 @@ func (e *Endpoint[TReq, TRes]) Handler() http.Handler {
6970
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
7071
var req TReq
7172

72-
if r.Body != nil {
73-
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
73+
data, err := io.ReadAll(r.Body)
74+
if err != nil {
75+
e.opts.errorHandler.HandleError(w, err)
76+
return
77+
}
78+
defer r.Body.Close()
79+
80+
if len(data) > 0 {
81+
if err := json.Unmarshal(data, &req); err != nil {
7482
e.opts.errorHandler.HandleError(w, err)
7583
return
7684
}
77-
78-
defer r.Body.Close()
7985
}
8086

8187
if extracter, ok := any(&req).(Extracter); ok {

xapi/endpoint_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,34 @@ func TestEndpoint_Handler(t *testing.T) {
4848
}`, rec.Body.String())
4949
})
5050

51+
t.Run("GetEndpoint", func(t *testing.T) {
52+
t.Parallel()
53+
54+
rec := httptest.NewRecorder()
55+
56+
handler := EndpointFunc[EmptyRequest, BasicResponse](
57+
func(ctx context.Context, req *EmptyRequest) (*BasicResponse, error) {
58+
return &BasicResponse{
59+
Message: "Hello Tester",
60+
ID: 321,
61+
}, nil
62+
},
63+
)
64+
65+
endpoint := NewEndpoint(handler)
66+
req := httptest.NewRequest(http.MethodGet, "/test?name=Tester", nil)
67+
req.Header.Set("Content-Type", "application/json")
68+
69+
endpoint.Handler().ServeHTTP(rec, req)
70+
71+
assert.Equal(t, http.StatusOK, rec.Result().StatusCode)
72+
assert.Equal(t, "application/json; charset=utf-8", rec.Header().Get("Content-Type"))
73+
assert.JSONEq(t, `{
74+
"message": "Hello Tester",
75+
"id": 321
76+
}`, rec.Body.String())
77+
})
78+
5179
t.Run("WithValidation", func(t *testing.T) {
5280
t.Parallel()
5381

@@ -443,6 +471,8 @@ func TestEndpoint_ContextCancellation(t *testing.T) {
443471

444472
// Test types and implementations
445473

474+
type EmptyRequest struct{}
475+
446476
type BasicRequest struct {
447477
Name string `json:"name"`
448478
}

0 commit comments

Comments
 (0)