我想在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)
}