h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

Home Page:https://pkg.go.dev/github.com/h2non/gock

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

is there any solution to generate response in the runtime?

CodeplayerGm opened this issue · comments

commented

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}")
  }
}
commented

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