before that I worked with node js and it was easy to understand how to handle methods
example on node js:
switch (request.method) {
case 'OPTIONS': return OptionsResponse(response);
case 'GET': return GetSwitch(request, response);
case 'POST': return PostSwitch(request, response);
case 'PUT': return PutSwitch(request, response);
case 'DELETE': return DeleteSwitch(request, response);
default: return ErrorMessage( "Sorry, this method not supported", 501, request);
}
but in go i can't figure out how to do it
package utils
import (
"log"
"net/http"
"github.com/user/go_rest_api/src/view" // page view
"github.com/user/go_rest_api/src/api" // only api server
);
How can I implement the same handler in go?
func HandlerRequestFunc() {
http.HandleFunc("/", view.Homepage);
/*get method from api server */
http.HandleFunc("/api", api.InfoFromApi);
/* from db api handler */
http.HandleFunc("/api/login", api.Login);
http.HandleFunc("/api/registration", api.Registration);
/* get your list db */
http.HandleFunc("/api/db/list", api.DataBaseList);
/* server start function */
log.Fatal(http.ListenAndServe(":3000", nil));
}
how not to process a method inside a function
CodePudding user response:
Here's the node.js code in the question translated to Go. The Go code is very similar to the node.js code.
func myHandler(response http.ResponseWriter, request *http.Request) {
switch request.Method {
case "OPTIONS":
OptionsResponse(response, request)
case "GET":
GetSwitch(response, request)
case "POST":
PostSwitch(response, request)
case "PUT":
PutSwitch(response, request)
case "DELETE":
DeleteSwitch(response, request)
default:
http.Error(response, "Sorry, this method not supported", 501)
}
}
CodePudding user response:
i think you need wiriting response and request for your code like this. because is the default package of the language
func myHandler(w http.ResponseWriter, r *http.Request) {
switch request.Method {
case "OPTIONS":
OptionsResponse(response, request)
case "GET":
GetSwitch(response, request)
case "POST":
PostSwitch(response, request)
case "PUT":
PutSwitch(response, request)
case "DELETE":
DeleteSwitch(response, request)
default:
http.Error(response, "Sorry, this method not supported", 501)
}
}