Skip to content

Instantly share code, notes, and snippets.

@riethm
Created September 16, 2016 13:53
Show Gist options
  • Save riethm/2b9caef1773ffcccdc98c4a014277145 to your computer and use it in GitHub Desktop.
Save riethm/2b9caef1773ffcccdc98c4a014277145 to your computer and use it in GitHub Desktop.
httpmock responder that cycles through a list of responses
import (
"net/http"
"github.com/jarcoal/httpmock"
)
func NewChainResponder(responders []httpmock.Responder) httpmock.Responder {
cursor := 0
return func(req *http.Request) (*http.Response, error) {
if len(responders) == 0 {
return nil, httpmock.NoResponderFound
}
next := responders[cursor]
cursor++
if cursor >= len(responders) {
cursor = 0
}
return next(req)
}
}
// ...
// Register a responder that responds differently to subsequent requests to the same URL
httpmock.RegisterResponder(
"GET",
baseURL + "/foo",
NewChainResponder([]httpmock.Responder{
httpmock.NewStringResponder(200, `[]`),
httpmock.NewStringResponder(500, ``),
httpmock.NewStringResponder(200, `[{"id": 1, "name": "bar"}]`),
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment