h2non / gock

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

is there any solution to generate response in the runtime? #107

Open CodeplayerGm opened 1 year ago

CodeplayerGm commented 1 year ago

since the "ReplyFunc()" provide an entrance to return a response generated by custom function. however, the "mockGithubResponseHandler" executes when the mocker is registered. is there any way to generate response in runtime, with parameter or options for "ReplyFunc()"?

gock.New("https://github.com").
  Post("/login/oauth/access_token").
  Persist().
  MatchParams(map[string]string{
    "client_id":     "Iv1.expire0000000000",
    "client_secret": "expire0000000000000000000000000000000000",
  }).
  ReplyFunc(mockGithubResponseHandler)

func mockGithubResponseHandler(r *gock.Response) {
  r.Status(200)
  r.SetHeader("Content-type", "application/json; charset=utf-8")
  if ExpireFlag {
    r.BodyString("{expire_at: 1670000000}")
  } else {
    r.BodyString("{expire_at: 0}")
  }
}
h2non commented 1 year ago

You can use .Map() in order to update the *http.Response directly: https://github.com/h2non/gock/blob/master/_examples/mapper/map.go