fix: correct index for embedded binary method receiver

When searching for a binary method on structures, look up on embedded
fields first, otherwise the resulting index is incorrect, as
reflect.Type.MethodByName succeeds also on container struct.

Fixes #834.
This commit is contained in:
Marc Vertes
2020-09-09 11:22:03 +01:00
committed by GitHub
parent 04770a4b81
commit 9ddecfa121
2 changed files with 60 additions and 10 deletions

52
_test/cli6.go Normal file
View File

@@ -0,0 +1,52 @@
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
)
type T struct {
http.ResponseWriter
}
type mw1 struct {
next http.Handler
}
func (m *mw1) ServeHTTP(rw http.ResponseWriter, rq *http.Request) {
t := &T{
ResponseWriter: rw,
}
x := t.Header()
fmt.Fprint(rw, "Welcome to my website!", x)
}
func main() {
m1 := &mw1{}
mux := http.NewServeMux()
mux.HandleFunc("/", m1.ServeHTTP)
server := httptest.NewServer(mux)
defer server.Close()
client(server.URL)
}
func client(uri string) {
resp, err := http.Get(uri)
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}
// Output:
// Welcome to my website!map[]

View File

@@ -1244,21 +1244,19 @@ func (t *itype) lookupBinMethod(name string) (m reflect.Method, index []int, isP
if t.cat == ptrT {
return t.val.lookupBinMethod(name)
}
for i, f := range t.field {
if f.embed {
if m2, index2, isPtr2, ok2 := f.typ.lookupBinMethod(name); ok2 {
index = append([]int{i}, index2...)
return m2, index, isPtr2, ok2
}
}
}
m, ok = t.TypeOf().MethodByName(name)
if !ok {
m, ok = reflect.PtrTo(t.TypeOf()).MethodByName(name)
isPtr = ok
}
if !ok {
for i, f := range t.field {
if f.embed {
if m2, index2, isPtr2, ok2 := f.typ.lookupBinMethod(name); ok2 {
index = append([]int{i}, index2...)
return m2, index, isPtr2, ok2
}
}
}
}
return m, index, isPtr, ok
}