Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions xapi/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package xapi
import (
"context"
"encoding/json"
"io"
"net/http"
)

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

if r.Body != nil {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
data, err := io.ReadAll(r.Body)
if err != nil {
e.opts.errorHandler.HandleError(w, err)
return
}
defer r.Body.Close()

if len(data) > 0 {
if err := json.Unmarshal(data, &req); err != nil {
e.opts.errorHandler.HandleError(w, err)
return
}

defer r.Body.Close()
}

if extracter, ok := any(&req).(Extracter); ok {
Expand Down
30 changes: 30 additions & 0 deletions xapi/endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,34 @@ func TestEndpoint_Handler(t *testing.T) {
}`, rec.Body.String())
})

t.Run("GetEndpoint", func(t *testing.T) {
t.Parallel()

rec := httptest.NewRecorder()

handler := EndpointFunc[EmptyRequest, BasicResponse](
func(ctx context.Context, req *EmptyRequest) (*BasicResponse, error) {
return &BasicResponse{
Message: "Hello Tester",
ID: 321,
}, nil
},
)

endpoint := NewEndpoint(handler)
req := httptest.NewRequest(http.MethodGet, "/test?name=Tester", nil)
req.Header.Set("Content-Type", "application/json")

endpoint.Handler().ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Result().StatusCode)
assert.Equal(t, "application/json; charset=utf-8", rec.Header().Get("Content-Type"))
assert.JSONEq(t, `{
"message": "Hello Tester",
"id": 321
}`, rec.Body.String())
})

t.Run("WithValidation", func(t *testing.T) {
t.Parallel()

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

// Test types and implementations

type EmptyRequest struct{}

type BasicRequest struct {
Name string `json:"name"`
}
Expand Down