I want to make a controller struct
in GoLang that has a ServeHTTP
method which calls its own methods (which responds with a 405
status code) based on that of the HTTP request. New controllers should be able to inherit ServeHTTP
while also being able to override methods like Get(w http.ResponseWriter, r *http.Request)
and have the new ones being triggered by ServeHTTP
. Then, controllers can be assigned as route handlers with the http module. I know how to do this in Java (have a controller superclass with all basic methods), but the method overriding part fails in Go. Here is my code:
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)
}