我想在 GoLang 中制作一个 Controller struct
,它有一个 ServeHTTP
方法,该方法调用它自己的方法(以 405
状态响应代码)基于 HTTP 请求的代码。新的 Controller 应该能够继承 ServeHTTP
,同时也能够覆盖 Get(w http.ResponseWriter, r *http.Request)
等方法并触发新的方法通过 ServeHTTP
。然后,可以使用 http 模块将 Controller 指定为路由处理程序。我知道如何在 Java 中执行此操作(有一个包含所有基本方法的 Controller 父类(super class)),但方法覆盖部分在 Go 中失败。这是我的代码:
package main
import "net/http"
type Controller struct { }
func notAllowed(w http.ResponseWriter){
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405- Method Not Allowed"))
}
func(c Controller) Get(w http.ResponseWriter, r *http.Request){
notAllowed(w)
}
func(c Controller) Post(w http.ResponseWriter, r *http.Request){
notAllowed(w)
}
func(c Controller) Put(w http.ResponseWriter, r *http.Request){
notAllowed(w)
}
func(c Controller) Patch(w http.ResponseWriter, r *http.Request){
notAllowed(w)
}
func(c Controller) Delete(w http.ResponseWriter, r *http.Request){
notAllowed(w)
}
func(c Controller) ServeHTTP(w http.ResponseWriter, r *http.Request){
switch r.Method {
case "GET":
c.Get(w, r)
case "POST":
c.Post(w, r)
case "PUT":
c.Put(w, r)
case "PATCH":
c.Patch(w, r)
case "DELETE":
c.Delete(w, r)
}
}
type Index struct {
Controller
}
func(I Index) Get(w http.ResponseWriter, r http.Request){
w.Write([]byte("hello"))
}
func main(){
http.Handle("/", Index{})
http.ListenAndServe(":8080", nil)
}
最佳答案
感谢@mkopriva;这是他在评论中给出的答案: https://play.golang.org/p/1-LEOjTo0AX
显然方法只会被反向组合覆盖。
关于http - 如何覆盖 GoLang 中的组合结构方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352734/