webtorrent / bittorrent-tracker

🌊 Simple, robust, BitTorrent tracker (client & server) implementation
https://webtorrent.io
MIT License
1.78k stars 319 forks source link

The tracker server is not conducive towards custom http endpoints #331

Closed guanzo closed 5 years ago

guanzo commented 5 years ago

Context

https://github.com/webtorrent/bittorrent-tracker/blob/5b9da4a5e2b4e64471e6b20f645f300cd0258997/server.js#L66-L73

Thanks for letting me add my own http handlers, but in order to handle the request in an async manner, I'm forced to synchronously call res.writeHead(200), so that res.headersSent === true, which prevents the other handlers from ending the request. It's quite awkward. My http response is forced to always return 200 just so I can "claim" the request before the other handlers.

I suppose I could fork the project and modify this.onHttpRequest(req, res), but I want to add the custom http endpoints in userland.

Is there a way around this? Am I doing this wrong? My experience with node http servers has only ever been thru the express API, so I'm not used to the native http api.

feross commented 5 years ago

We exposed this.onHttpRequest publicly so that you can override it. I believe you can do this:

const origOnHttpRequest = server.onHttpRequest.bind(server)
server.onHttpRequest = (req, res, opts = {}) => {
  someAsyncApi(() => {
    if (cond) {
      // .. handle request yourself
    } else {
      // default handler
      origOnHttpRequest(req, res, opts)
    }    
  })
}

Hope this works for you :) I'm closing this issue since there's no bug to fix here, but feel free to continue discussion! ✨

guanzo commented 5 years ago

Got it thanks, that should work. Although I believe onHttpRequest is a method of server, not server.http

feross commented 5 years ago

Nice. Wrote the code from memory :) Will update it for the sake of future users coming from web search.