Last active
December 18, 2017 12:02
-
-
Save rheinardkorf/687aaf1b5adff9814cf3f07e534219f1 to your computer and use it in GitHub Desktop.
A very rugged way to do some mock endpoints with routes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example | |
import ( | |
"testing" | |
"net/http/httptest" | |
"net/http" | |
"fmt" | |
"io/ioutil" | |
) | |
// mockHandler implements http.Handler and is used to mock 3rd party | |
// endpoints. | |
// | |
// routes is a basic router implementation to make testing a bit easier to implement. | |
type mockHandler struct { | |
routes map[string]func(http.ResponseWriter, *http.Request) | |
} | |
// mockRouter is an instance of mockHandler and is used in our tests to add new routes | |
// to test. | |
var mockRouter = &mockHandler{ | |
routes: make(map[string]func(http.ResponseWriter, *http.Request)), | |
} | |
// mockServer is an instance of a httpstest.Server and used to stub out the 3rd party endpoints. | |
var mockServer = httptest.NewServer(mockRouter) | |
// ServerHTTP implements the requirements for an http.Handler. | |
func (m mockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
route := r.URL.String() + ":" + r.Method | |
if m.routes[route] != nil { | |
m.routes[route](w, r) | |
} else { | |
fmt.Fprint(w, "unknown route") | |
} | |
} | |
// Dynamically add new routes to ServeHTTP via the routes map. | |
func (m *mockHandler) HandleFunc(route, method string, f func(http.ResponseWriter, *http.Request)) { | |
m.routes[route + ":" + method] = f | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment