Go语言 如何在gRPC网关中配置公共路由和授权路由

qfe3c7zg  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(92)

gRPC gateway有没有办法像其他http框架一样配置public route和auth route,比如在echo框架中可以这样配置

func main() {
    e := echo.New()
    authRoute := e.Group("/auth", middlewares.Verify)
    publicRoute := e.Group("/")
    // ...
}

字符串
在grpc-gateway中,我有这样配置。

func run() error {
  ctx := context.Background()
  ctx, cancel := context.WithCancel(ctx)
  defer cancel()

  // Register gRPC server endpoint
  // Note: Make sure the gRPC server is running properly and accessible
  mux := runtime.NewServeMux()
  opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
  err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux,  *grpcServerEndpoint, opts)
  if err != nil {
    return err
  }

  // Start HTTP server (and proxy calls to gRPC server endpoint)
  return http.ListenAndServe(":8081", mux)
}


有没有什么方法可以让mux为特定的路由提供认证的装饰器函数。并且函数RegisterYourServiceHandlerFromEndpoint将注册它

authenMux := runtime.NewServeMux()
// make it with authenticated func
//....

err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, authenMux,  *grpcServerEndpoint, opts)

llycmphe

llycmphe1#

我不确定你的具体目标,但如果你只想定制gRPC网关,你可以按照这种方法。或者,你可以将逻辑转移到一个单独的函数。

// run starts the HTTP server and sets up a custom gRPC-gateway route.
// It registers the gRPC server endpoint and a custom POST route ("/auth").
func run() error {
    // Create a background context and cancel function for graceful shutdown
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    // Create a gRPC-gateway multiplexer
    mux := runtime.NewServeMux()

    // Register gRPC server endpoint with insecure transport credentials
    opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
    err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
    if err != nil {
        return err
    }

    // Handle custom POST route ("/auth")
    err = mux.HandlePath("POST", "/auth", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
        // Create a map with the desired data
        responseData := map[string]string{
            "data": "something",
        }

        // Convert the map to a JSON string
        resp, err := json.Marshal(responseData)
        if err != nil {
            http.Error(w, "Error encoding JSON", http.StatusInternalServerError)
            return
        }

        // Set the Content-Type header to application/json
        w.Header().Set("Content-Type", "application/json")

        // Write the JSON response to the response writer
        w.Write(resp)
    })

    if err != nil {
        return err
    }

    // Start HTTP server (and proxy calls to gRPC server endpoint)
    return http.ListenAndServe(":8081", mux)
}

字符串

相关问题