I have REST HTTP handlers implemented with gorilla/mux. I am trying to migrate them into gRPC. There are some handlers doing file upload and download. So, my client decided to implement those handlers in gRPC gateway.
One of my mux handler handles multiple HTTP methods and do stuffs according to HTTP method in one handler func. Example code is like below.
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc(`/doSomething`, func(writer http.ResponseWriter, request *http.Request) {
switch request.Method {
case http.MethodPost:
// create something
fmt.Fprint(writer, "POST")
case http.MethodGet:
// return something
fmt.Fprint(writer, "GET")
case http.MethodPut:
// update something
fmt.Fprint(writer, "PUT")
case http.MethodDelete:
// delete something
fmt.Fprint(writer, "DELETE")
}
})
http.ListenAndServe(`:5000`, r)
}
When I implemented similar grpc gateway mux handler to handle those requests with grpc-ecosystem/grpc-gateway/v2.3.0, I have to write separate handler functions to handle different HTTP methods to same path. Example code like below.
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"net/http"
)
func main() {
r := mux.NewRouter()
grpcGatewayHandler := runtime.NewServeMux()
r.PathPrefix("/").Handler(grpcGatewayHandler)
_ = grpcGatewayHandler.HandlePath(`POST`, `/doSomething`,
func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
fmt.Fprint(w, "POST")
})
_ = grpcGatewayHandler.HandlePath(`PUT`, `/doSomething`,
func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
fmt.Fprint(w, "PUT")
})
_ = grpcGatewayHandler.HandlePath(`GET`, `/doSomething`,
func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
fmt.Fprint(w, "GET")
})
_ = grpcGatewayHandler.HandlePath(`DELETE`, `/doSomething`,
func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
fmt.Fprint(w, "DELETE")
})
http.ListenAndServe(`:5000`, r)
}
I couldn't find any alternative solution to use different methods in same handler func.
- Is there any way to handle different methods in one handler with grpc-gateway?
- Is there no difference between handling methods separately and in one handler func?