gock icon indicating copy to clipboard operation
gock copied to clipboard

access request body from ReplyFunc ?

Open helmus opened this issue 4 years ago • 6 comments

Is it possible to access the request body in the ReplyFunc ?

gock.New(myEndpoint).
	Post("/scim/v2/Groups").
	Persist().
	ReplyFunc(func(response *gock.Response) {
		response.???
	})

helmus avatar Mar 29 '20 20:03 helmus

Yes:

gock.New(myEndpoint).
	Post("/scim/v2/Groups").
	Persist().
	ReplyFunc(func(response *gock.Response) {
		req := response.Mock.Request()
	})

h2non avatar Mar 29 '20 21:03 h2non

If you want to use an ad-hoc request match logic based on the arbitrary body contents, you should use a custom matcher function:

gock.New(myEndpoint).
	Post("/scim/v2/Groups").
	Persist().
        MatchFunc(func (req *http.Request, ereq *gock.Request) (bool, error) {
           // do request body matching here
           return true, nil
        })

h2non avatar Mar 29 '20 21:03 h2non

@h2non how can I then use the request object to read the request body ? req.BodyBuffer is an empty string ?

gock.New(myEndpoint).
	Post("/scim/v2/Groups").
	Persist().
	ReplyFunc(func(response *gock.Response) {
		req := response.Mock.Request()
                log.Printf("REQUEST BODY %v",string(req.BodyBuffer)) 
	})

EDIT: Can I then use what I matched with in MatchFunc, to reply with in ReplyFunc ? Or would I have to do the mapping outside of gock with a shared map or something ?

helmus avatar Mar 29 '20 21:03 helmus

Well, you cannot do that at that level, but you can use the generic gock.Observe(observer) to track matched outgoing requests, read the body and do your own state mapping outside gock primitives.

h2non avatar Mar 29 '20 21:03 h2non

Great ! Thanks for replying Tom, really appreciate it ! This gives me enough info to proceed.

helmus avatar Mar 29 '20 21:03 helmus

@helmus Could you share an example of how you used gock.Observe(observer) to accomplish reading the request body?

FabianGrupp avatar Jul 21 '21 13:07 FabianGrupp