Grpc-gateway: Use Echo/Gin as request multiplexer

Created on 8 Oct 2018  路  3Comments  路  Source: grpc-ecosystem/grpc-gateway

Is that possible using echo/gin/httprouter as request multiplexer instead of runtime.ServeMux?

enhancement question

Most helpful comment

This is a little older but I had the same question. Here's how you do it in chi:


    mux := runtime.NewServeMux()
    opts := []grpc.DialOption{grpc.WithInsecure()}
    err = apiv1.RegisterXXXXXHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%s", env.GRPCServerPort), opts)
    if err != nil {
        return err
    }

    r := chi.NewRouter()
    r.HandleFunc("/api/*", func(w http.ResponseWriter, r *http.Request) {
        // gateway is generated to match for /v1/ and not /api/v1
        // we could update the gateway proto to match for /api/v1 but
        // it shouldn't care where it's mounted to, hence we just rewrite the path here
        r.URL.Path = strings.Replace(r.URL.Path, "/api", "", -1)
        mux.ServeHTTP(w, r)
    })

In short, make sure that either gateway is generated to match the correct URLs or use a handler to replace whatever prefix you added

All 3 comments

Not currently as far as I know. The runtime.ServeMux implements http.Handler though, so you can use your own router and only use the ServeMux to handle a subset of routes.

@rexlv,
Here is my implementation of @johanbrandhorst's suggestion, a working example of Gin-gonic and grpc-gateway.

This is a little older but I had the same question. Here's how you do it in chi:


    mux := runtime.NewServeMux()
    opts := []grpc.DialOption{grpc.WithInsecure()}
    err = apiv1.RegisterXXXXXHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%s", env.GRPCServerPort), opts)
    if err != nil {
        return err
    }

    r := chi.NewRouter()
    r.HandleFunc("/api/*", func(w http.ResponseWriter, r *http.Request) {
        // gateway is generated to match for /v1/ and not /api/v1
        // we could update the gateway proto to match for /api/v1 but
        // it shouldn't care where it's mounted to, hence we just rewrite the path here
        r.URL.Path = strings.Replace(r.URL.Path, "/api", "", -1)
        mux.ServeHTTP(w, r)
    })

In short, make sure that either gateway is generated to match the correct URLs or use a handler to replace whatever prefix you added

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fifthaxe picture fifthaxe  路  5Comments

pzsfeng picture pzsfeng  路  5Comments

djavorszky picture djavorszky  路  5Comments

danforbes picture danforbes  路  4Comments

boosh picture boosh  路  5Comments