如何在GoLang中覆盖组合的struct方法

时间:2018-07-15 22:40:22

标签: http oop go routing method-overriding

我想在GoLang中创建一个控制器struct,该控制器具有一个ServeHTTP方法,该方法根据HTTP请求的方法调用自己的方法(以状态405响应) 。新的控制器应该能够继承ServeHTTP,同时也能够覆盖Get(w http.ResponseWriter, r *http.Request)之类的方法,并使新的控制器由ServeHTTP触发。然后,可以使用http模块将控制器分配为路由处理程序。我知道如何在Java中执行此操作(拥有一个具有所有基本方法的控制器超类),但是方法重写部分在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)
}

1 个答案:

答案 0 :(得分:1)

谢谢@mkopriva;这是他在评论中提出的答案: https://play.golang.org/p/1-LEOjTo0AX

显然,方法只会被反向组合覆盖。