Skip to content

Instantly share code, notes, and snippets.

@soheilhy soheilhy/cmux_example.go
Last active Aug 29, 2015

What would you like to do?
cmux example
// Create the main listener.
lis, err := net.Listen("tcp", ":23456")
if err != nil {
// Create a cmux.
mux := cmux.New(lis)
// Match connections in order:
// First grpc, then HTTP, and otherwise Go RPC/TCP.
grpcL := mux.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
httpL := mux.Match(cmux.HTTP1Fast())
trpcL := mux.Match(cmux.Any()) // Any means anything that is not yet matched.
// Create your protocol servers.
// The gRPC server.
grpcS := grpc.NewServer()
grpchello.RegisterGreeterServer(grpcs, &server{})
// The HTTP server.
httpS := &http.Server{Handler: &helloHTTP1Handler{}}
// The GoRPC/TCP server.
trpcS := rpc.NewServer()
// Use the muxed listeners for your servers.
go grpcS.Serve(grpcL)
go httpS.Serve(httpL)
go trpcS.Accept(trpcL)
// Start serving!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.