h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
https://pkg.go.dev/github.com/h2non/gock
MIT License
2.1k stars 107 forks source link

access request body from ReplyFunc ? #65

Open helmus opened 4 years ago

helmus commented 4 years ago

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.???
    })
h2non commented 4 years ago

Yes:

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

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
        })
helmus commented 4 years ago

@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 ?

h2non commented 4 years ago

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.

helmus commented 4 years ago

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

FabianGrupp commented 3 years ago

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