Embedding the resgate server?

Hi, is it possible to embed the resgate server in another Go app and perhaps tie the http handler into a URL? Or does it need to own the entire http server?

I’m currently embedding the nats server:

One goal I have with my project is to make it simple to deploy for smaller systems – you deploy one binary and you have an entire system, vs operating 3-5 services.

Welcome to the forum :partying_face:!

…and sorry for the delayed response. Busy weekend.

Yes. It is not really made for it, but it is possible as is. The API could surely be improved to simplify it. Anyway.

Embedding and starting an instance is simple. In main.go, you can see how to create the Resgate server instance and start it:

So the imports are:

  • github.com/resgateio/resgate/server - the main Resgate package
  • github.com/resgateio/resgate/nats - a wrapper to nats client that implements the client interface, which Resgate uses for all NATS communication. You can perhaps speed things up by making your own wrapper that directly communicates with the embedded nats-server, without using networking? Otherwise you just use this.
  • github.com/resgateio/resgate/logger - a logger interface. If you have some other sort of logger, you may want to create your implementation of this interface. But you can use this one.

Then we need to prevent Resgate from starting its own HTTP server, which is done by setting the NoHTTP bool flag in the Config struct to true before you pass it on to server.NewService.

Now you just have to start your own http.Server in your application and pass any request aimed for Resgate (or any request that your server doesn’t handle) to the service.ServeHTTP method. Because the Resgate service instance implements the http.Handler interface:

Hope that helps. And tell me if you made it work! I’ve never tried it myself :grin:

Best regards,

Thanks for the detailed information!

1 Like