I am getting this error because I have registered the same endpoint twice. But, I want to have them with different methods.
GET for fetching data
POST for adding new data.
Any idea how to implement this?
package main
import (
"fmt"
"net/http"
)
func usrGet(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET user")
w.Write([]byte("GET user"))
}
func usrAdd(w http.ResponseWriter, r *http.Request) {
fmt.Println("add User")
w.Write([]byte("add user"))
}
func main() {
mux := NewRoute()
mux.Endpoint("GET", "/user", usrGet)
mux.Endpoint("POST", "/user", usrAdd)
http.ListenAndServe(":8888", mux)
}
type Route struct {
*http.ServeMux
}
func NewRoute() *Route {
return &Route{http.NewServeMux()}
}
func (r *Route) Endpoint(verb, path string, handler http.HandlerFunc) {
r.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { // <<<< The issue comes from this line
if r.Method != verb {
fmt.Println("method:", r.Method)
w.WriteHeader(http.StatusBadRequest)
return
}
handler(w, r)
})
}
func (r *Route) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.ServeHTTP(w, req)
}
