resty icon indicating copy to clipboard operation
resty copied to clipboard

RawRequest is nil in BeforeOnRequest method

Open belek opened this issue 2 years ago • 2 comments

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?

belek avatar Jan 31 '22 10:01 belek

Just share what I found.

There are three types of request middleware, and they are performed in sequence:

  1. udBeforeRequest chain (registered by Client.onBeforeRequest)
  2. beforeRequest chain (default middleware registered by resty)
  3. preReqHook hook (registered by Client.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 avatar May 07 '22 05:05 0140454

@0140454 great thanks, just faced exactly the same issue : D

x-EricH-x avatar Jul 23 '22 12:07 x-EricH-x

@belek Please use the SetPreRequestHook. @0140454 mentioned the correct execution sequence.

jeevatkm avatar Sep 17 '23 08:09 jeevatkm