Last active
August 29, 2015 14:26
-
-
Save soheilhy/971da583d8b1414acb8a to your computer and use it in GitHub Desktop.
cmux example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create the main listener. | |
lis, err := net.Listen("tcp", ":23456") | |
if err != nil { | |
log.Fatal(err) | |
} | |
// 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() | |
s.Register(&ExampleRPCRcvr{}) | |
// Use the muxed listeners for your servers. | |
go grpcS.Serve(grpcL) | |
go httpS.Serve(httpL) | |
go trpcS.Accept(trpcL) | |
// Start serving! | |
mux.Serve() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment