我有使用 gorilla/mux 实现的 REST HTTP 处理程序。我正在尝试将它们迁移到 gRPC 中。有一些处理程序进行文件上传和下载。因此,我的客户决定在 gRPC 网关中实现这些处理程序。
我的一个 mux 处理程序处理多个 HTTP 方法,并根据一个处理程序函数中的 HTTP 方法执行操作。示例代码如下。
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)
}
当我使用 grpc-ecosystem/grpc-gateway/v2.3.0 实现类似的 grpc 网关 mux 处理程序来处理这些请求时,我必须编写单独的处理程序函数来处理不同的 HTTP 方法到相同的路径。示例代码如下。
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)
}
我找不到任何替代解决方案来在同一个处理函数中使用不同的方法。
你的原型文件会是这样的
syntax = "proto3";
import "google/api/annotations.proto";
import "google/api/httpbody.proto";
service SampleService {
rpc doSomethingPost (Request) returns (google.api.HttpBody) {
option (google.api.http) = {
post: "/doSomething"
};
}
rpc doSomethingPUT (Request) returns (google.api.HttpBody) {
option (google.api.http) = {
put: "/doSomething"
};
}
rpc doSomethingGet (Request) returns (google.api.HttpBody) {
option (google.api.http) = {
get: "/doSomething"
};
}
}