Reputation: 10329
Is it possible for a GRPC server written in golang to also handle REST requests?
I've found the grpc-gateway which enables turning an existing proto schema into a rest endpoint but I don't think that suits my needs.
I've written a GRPC server but I need to also serve webhook requests from an external service (like Github or Stripe). I'm thinking of writing a second REST based server to accept these webhooks (and possibly translate/forward them to the GRPC server) but that seems like a code-smell.
Ideally, I'd like for my GRPC server to also be able to, for example, handle REST requests at an endpoint like /webhook
or /event
but I'm not sure if that's possible and if it is how to configure it.
Upvotes: 1
Views: 1548
Reputation: 10329
Looks like I asked my question before giving a large enough effort to resolve it my own. Here's an example of serving REST requests alongside GRPC requests
func main() {
lis, err := net.Listen("tcp", ":6789")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// here we register and HTTP server listening on port 6789
// note that we do this in with gofunc so that the rest of this main function can execute - this probably isn't ideal
http.HandleFunc("/event", Handle)
go http.Serve(lis, nil)
// now we set up GRPC
grpcServer := grpc.NewServer()
// this is a GRPC service defined in a proto file and then generated with protoc
pipelineServer := Server{}
pipeline.RegisterPipelinesServer(grpcServer, pipelineServer)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}
func Handle(response http.ResponseWriter, request *http.Request) {
log.Infof("handling")
}
With the above, sending a POST
to localhost:6789/event
will cause the handling
log line to be emitted.
Upvotes: 1