From 8adc3e30880639eb21f1b1b1fa829d64e755db66 Mon Sep 17 00:00:00 2001 From: longit644 Date: Sun, 17 Dec 2023 09:46:57 +0700 Subject: [PATCH] feat(jsonrpc): add method to retrieve request ID from context Signed-off-by: longit644 --- transport/http/jsonrpc/server.go | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/transport/http/jsonrpc/server.go b/transport/http/jsonrpc/server.go index f35caefb7..d144a961c 100644 --- a/transport/http/jsonrpc/server.go +++ b/transport/http/jsonrpc/server.go @@ -15,6 +15,25 @@ type requestIDKeyType struct{} var requestIDKey requestIDKeyType +// RequestIDFromContext returns the request id from context. +func RequestIDFromContext(ctx context.Context) *RequestID { + if ctx == nil { + return nil + } + + v := ctx.Value(requestIDKey) + if v == nil { + return nil + } + + vv, ok := v.(*RequestID) + if !ok { + return nil + } + + return vv +} + // Server wraps an endpoint and implements http.Handler. type Server struct { ecm EndpointCodecMap @@ -198,12 +217,8 @@ func DefaultErrorEncoder(ctx context.Context, err error, w http.ResponseWriter) w.WriteHeader(http.StatusOK) - var requestID *RequestID - if v := ctx.Value(requestIDKey); v != nil { - requestID = v.(*RequestID) - } _ = json.NewEncoder(w).Encode(Response{ - ID: requestID, + ID: RequestIDFromContext(ctx), JSONRPC: Version, Error: &e, })