From 990afc8fb3d5be816ed55cdaa023f65e04978850 Mon Sep 17 00:00:00 2001 From: Jasmin Oster Date: Thu, 23 Nov 2023 10:04:02 +0100 Subject: [PATCH] fixup! Implement typed request data using generics --- handler.go | 19 ++++++++++++------- mux.go | 6 +----- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/handler.go b/handler.go index 64804fe..985dd06 100644 --- a/handler.go +++ b/handler.go @@ -3,6 +3,7 @@ package e5e import ( "context" "encoding/json" + "fmt" ) // A Handler responds to a request. @@ -39,12 +40,11 @@ func (h handlerFunc[T, TContext]) Handle(ctx context.Context, evt Request[T, TCo // invoked with a Request[T]) in such a way as to make it non-generic so that it can // be used in other non-generic code like [Mux]. type handlerFactory interface { - // UnmarshalJob unmarshals the request to the internal state of the factory and returns any errors. - UnmarshalJob(payload []byte) error - - // Execute the handler with the internal request state. - // Only called after UnmarshalJob. - Execute(ctx context.Context) (*Result, error) + // Execute the handler with payload, which should be a deserializable JSON object. + // Any errors that occur due to deserialization or otherwise are returned. + // + // It is safe to call this method from multiple goroutines if the underlying [Handler] is. + Execute(ctx context.Context, payload []byte) (*Result, error) } type typedHandlerFactory[T, TContext Data] struct { @@ -56,6 +56,11 @@ func (t *typedHandlerFactory[T, TContext]) UnmarshalJob(data []byte) error { return json.Unmarshal(data, &t.request) } -func (t *typedHandlerFactory[T, TContext]) Execute(ctx context.Context) (*Result, error) { +func (t *typedHandlerFactory[T, TContext]) Execute(ctx context.Context, payload []byte) (*Result, error) { + var request Request[T, TContext] + if err := json.Unmarshal(payload, &request); err != nil { + return nil, fmt.Errorf("unmarshaling JSON failed: %w", err) + } + return t.h.Handle(ctx, t.request) } diff --git a/mux.go b/mux.go index 251e04d..8b762b0 100644 --- a/mux.go +++ b/mux.go @@ -175,11 +175,7 @@ func (m *Mux) execute(ctx context.Context, payload []byte) (string, error) { } factory := m.handlers[m.Options.Entrypoint] - if err := factory.UnmarshalJob(payload); err != nil { - return "", fmt.Errorf("unmarshalling request into request: %w", err) - } - - res, err := factory.Execute(ctx) + res, err := factory.Execute(ctx, payload) if err != nil { return "", fmt.Errorf("handler execution: %w", err) }