I'm trying to write a function getTargetServer()
to return a polymorphic type that has both a data member URL
and a method Close()
. This would be a generalization of the *Server
returned from httptest.NewServer()
but I want to alternatively be able to return a custom type for which Close()
is a NOP.
type externalTestServer struct {
URL string
}
func (externalTestServer) Close() {}
func getTargetServer() *externalTestServer {
if urlbase, ok := optionals["urlbase"].(string); ok {
return &externalTestServer{URL: urlbase}
} else {
testServer := httptest.NewServer(newMyServerHandler())
// return testServer // ### Error ###
return &externalTestServer{URL: testServer.URL}
}
}
func Test_health_check(t *testing.T) {
testServer := getTargetServer()
defer testServer.Close()
response, err := http.Get(testServer.URL + "/health")
assert.NilError(t, err)
assert.Assert(t, cmp.Equal(response.StatusCode, http.StatusOK))
}
This works like a charm except that Close()
is always a NOP. When I uncomment the indicated ### Error ###
line in order to return a closable *Server
, I get the following error message:
cannot use testServer (type *httptest.Server) as type *externalTestServer in return argument
I understand the error, but haven't discovered a solution that lets me return a polymorphic type that generalizes *Server
Note: "A Tour of Go" defines an interface type as follows:
An interface type is defined as a set of method signatures.
Therefore, returning a simple interface will not allow for directly-accessible data members.