我有这个控制器:
\n\npackage web\n\nimport (\n "net/http"\n)\n\nfunc init() {\n\n}\n\nfunc (controller *Controller) Index(r *http.Request) (string, int) {\n return "Testing", http.StatusOK\n}\nRun Code Online (Sandbox Code Playgroud)\n\n使用此处理程序:
\n\ntype Application struct {\n}\n\nfunc (application *Application) Route(controller interface{}, route string) http.HandlerFunc {\n return func(w http.ResponseWriter, r *http.Request) {\n\n var ptr reflect.Value\n var value reflect.Value\n var finalMethod reflect.Value\n\n value = reflect.ValueOf(controller)\n\n // if we start with a pointer, we need to get value pointed to\n // if we start with a value, we need to get a pointer to that value\n if value.Type().Kind() == reflect.Ptr {\n ptr = value\n value = ptr.Elem()\n } else {\n ptr = reflect.New(reflect.TypeOf(controller))\n temp := ptr.Elem()\n temp.Set(value)\n }\n\n // check for method on value\n method := value.MethodByName(route)\n if method.IsValid() {\n finalMethod = method\n }\n // check for method on pointer\n method = ptr.MethodByName(route)\n if method.IsValid() {\n finalMethod = method\n }\n\n methodInterface := finalMethod.Call([]reflect.Value{})[0].Interface()\n method_route := methodInterface.(func(r *http.Request) (string, int))\n body, code := method_route(r)\n switch code {\n case http.StatusOK:\n io.WriteString(w, body)\n case http.StatusSeeOther, http.StatusFound:\n http.Redirect(w, r, body, code)\n default:\n w.WriteHeader(code)\n io.WriteString(w, body)\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n它是这样执行的:
\n\ncontroller := &web.Controller{}\napplication := &system.Application{}\n\nhttp.HandleFunc("/", application.Route(controller, "Index"))\nRun Code Online (Sandbox Code Playgroud)\n\n问题是编译没问题。它没有显示任何错误,但是当我访问该网站时,只需指向 localhost,它就会显示:
\n\n2014/12/27 22:38:16 http: panic serving 127.0.0.1:58304: reflect: Call with too few input arguments\ngoroutine 20 [running]:\nnet/http.func\xc2\xb7011()\n /usr/local/Cellar/go/1.3.3/libexec/src/pkg/net/http/server.go:1100 +0xb7\nRun Code Online (Sandbox Code Playgroud)\n\n我找不到任何错误,更奇怪的是它编译正常...我是 Go 新手,所以我不知道发生了什么...
\n我通过阅读这篇文章找到了答案:
因此,不要尝试调用该方法:
methodInterface := finalMethod.Call([]reflect.Value{})[0].Interface()
method_route := methodInterface.(func(r *http.Request) (string, int))
body, code := method_route(r)
Run Code Online (Sandbox Code Playgroud)
我只是获得我需要的接口,然后将其转换为函数并这样调用它。
methodInterface := finalMethod.Interface()
method_route := methodInterface.(func(r *http.Request) (string, int))
body, code := method_route(r)
Run Code Online (Sandbox Code Playgroud)
事实上,这就是我已经在做的事情,但方式错误。
| 归档时间: |
|
| 查看次数: |
5371 次 |
| 最近记录: |