Skip to content

Instantly share code, notes, and snippets.

@dhrp
Created February 21, 2018 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhrp/44d371864f7e2508d128bc287c238308 to your computer and use it in GitHub Desktop.
Save dhrp/44d371864f7e2508d128bc287c238308 to your computer and use it in GitHub Desktop.
Main function for grpc-gateway REST and gRPC muxed on a simgle port
func main() {
keyPair, certPool := certificates.GetCert()
grpcServer := makeGRPCServer(certPool)
restMux, err := getRestMux(certPool)
if err != nil {
log.Panic(err)
}
// register root Http multiplexer (mux)
mux := http.NewServeMux()
// we can add any additional non-grpc endpoints here.
mux.HandleFunc("/foobar/", simpleHTTPHello)
// register the gateway mux onto the root path.
mux.Handle("/", restMux)
// the grpcHandlerFunc takes an grpc server and a http muxer and will
// route the request to the right place at runtime.
mergeHandler := grpcHandlerFunc(grpcServer, mux)
// configure TLS for our server. TLS is REQUIRED to make this setup work.
// check https://golang.org/src/net/http/server.go?#L2746
srv := &http.Server{
Addr: serveAddress,
Handler: mergeHandler,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{*keyPair},
NextProtos: []string{"h2"},
},
}
// start listening on the socket
conn, err := net.Listen("tcp", serveAddress)
if err != nil {
panic(err)
}
// start the server
fmt.Printf("starting GRPC and REST on: %v\n", serveAddress)
err = srv.Serve(tls.NewListener(conn, srv.TLSConfig))
if err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment