resty
resty copied to clipboard
RawRequest is nil in BeforeOnRequest method
My goal is to store body from request to particular URLs. To do that I implemented OnBeforeRequest interceptor where I am trying to use httputil.DumpRequest to get the body and then save it to DB. But I can't use request.RawRequest because it's nil. Also I enabled debug mode in client.
func (irc *RestyResponseInterceptorNomad) OnBeforeRequest(rc *resty.Client, req *resty.Request) error {
fmt.Println("*** Is debug? ", rc.Debug)
fmt.Println("*** Raw request: ", req.RawRequest)
reqDump, err := httputil.DumpRequest(req.RawRequest, true)
if err != nil {
logrus.WithError(err).Error("failed to dump request in onAfterResponse method")
return nil
}
.....
.....
.....
return err
}
Output is:
*** Is debug? true
*** Raw request: <nil>
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
Why RawRequest is nil and what should I do to make it work well?
Just share what I found.
There are three types of request middleware, and they are performed in sequence:
-
udBeforeRequest
chain (registered byClient.onBeforeRequest
) -
beforeRequest
chain (default middleware registered by resty) -
preReqHook
hook (registered byClient.SetPreRequestHook
)
RawRequest
is initialized at the second chain. Therefore, we will get a nil
in our onBeforeRequest
function.
To access a valid Http.Request
instance, we need to register hook via Client.SetPreRequestHook
.
See also
- https://github.com/go-resty/resty/blob/v2.7.0/client.go#L899-L923
- https://github.com/go-resty/resty/blob/v2.7.0/client.go#L1096-L1102
@0140454 great thanks, just faced exactly the same issue : D
@belek Please use the SetPreRequestHook. @0140454 mentioned the correct execution sequence.