add Controller.Method(string) to interface the extraction of dynamic method

This commit is contained in:
Adrien Marquès 2018-05-24 16:22:29 +02:00
parent 8106c22dbd
commit 75db1513bb
2 changed files with 13 additions and 25 deletions

View File

@ -52,23 +52,24 @@ func IsMethodAvailable(method string) bool {
return false
}
// HasMethod returns whether the controller has a given
// method (case insensitive)
func (c Controller) HasMethod(method string) bool {
// Method returns whether the controller has a given
// method by name (case insensitive)
// NIL is returned if no method is found
func (c Controller) Method(method string) *Method {
method = strings.ToUpper(method)
switch method {
case "GET":
return c.GET != nil
return c.GET
case "POST":
return c.POST != nil
return c.POST
case "PUT":
return c.PUT != nil
return c.PUT
case "DELETE":
return c.DELETE != nil
return c.DELETE
default:
return false
return nil
}

View File

@ -8,7 +8,7 @@ import (
"strings"
)
func (s Server) route(res http.ResponseWriter, req *http.Request) {
func (s *Server) route(res http.ResponseWriter, req *http.Request) {
/* (1) Build request
---------------------------------------------------------*/
@ -53,10 +53,7 @@ func (s Server) route(res http.ResponseWriter, req *http.Request) {
/* (3) Check method
---------------------------------------------------------*/
/* (1) Unavailable method */
if req.Method == "GET" && ctl.GET == nil ||
req.Method == "POST" && ctl.POST == nil ||
req.Method == "PUT" && ctl.PUT == nil ||
req.Method == "DELETE" && ctl.DELETE == nil {
if !config.IsMethodAvailable(req.Method) {
Json, _ := ErrUnknownMethod.MarshalJSON()
res.Header().Add("Content-Type", "application/json")
@ -67,17 +64,7 @@ func (s Server) route(res http.ResponseWriter, req *http.Request) {
}
/* (2) Extract method cursor */
var method *config.Method
if req.Method == "GET" {
method = ctl.GET
} else if req.Method == "POST" {
method = ctl.POST
} else if req.Method == "PUT" {
method = ctl.PUT
} else if req.Method == "DELETE" {
method = ctl.DELETE
}
var method = ctl.Method(req.Method)
/* (3) Unmanaged HTTP method */
if method == nil { // unknown method
@ -90,7 +77,7 @@ func (s Server) route(res http.ResponseWriter, req *http.Request) {
/* (4) Check arguments
---------------------------------------------------------*/
for name, data := range request.Data {
for name, data := range s.Params {
fmt.Printf("- %s: %v\n", name, data)
}
fmt.Printf("\n")