How can I overwrite anonymous struct function.
To clarify what I mean look at the following code snippet:
package base
import (
"fmt"
"net/http"
)
type Executer interface {
Execute()
}
type Controller struct { }
func (self *Controller) Execute() {
fmt.Println("Hello Controller")
}
func (self *Controller) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
self.Execute()
}
Now I am embedding the Controller struct into Test struct, also called anonymous
package base
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
type Test struct {
Controller
}
func (self *Test) Execute() {
fmt.Println("Hello Test")
}
func TestInheritance(t *testing.T) {
ts := httptest.NewServer(&Test{})
defer ts.Close()
http.Get(ts.URL)
}
As output I've got "Hello Controller" but expected "Hello Test". You can see code above, I reimplement the execute function, but it does not work.
Since Test
has no ServeHTTP
method, your test server uses Controller
's, which calls Controller.Execute()
. If you want it to work properly, define ServeHTTP
for the Test
type.
type Test struct {
Controller
}
Controller
has no ServeHTTP
method but *Controller
has. So
type Test struct {
*Controller
}
I think it will work.