markusahlstrand / cloudworker-proxy

An api gateway for cloudflare workers
MIT License
194 stars 22 forks source link

Route based on method #63

Closed danbars closed 4 years ago

danbars commented 4 years ago

I have a need to route based on HTTP method and not just path. I thought maybe it's a good opportunity to use a more generic approach like this one: https://github.com/node-muneem/anumargak Or this one, that seem to be more maintained: https://github.com/delvedor/find-my-way Happy to contribute code if you like the idea. What do you think?

markusahlstrand commented 4 years ago

Hi @danbars ,

There is a similar router used today: https://www.npmjs.com/package/cloudworker-router I couldn't find any existing router that didn't have any dependencies that worked will with workers so I wrote a small one. It's been covering my use cases so far, but if there's something missing it should be easy to add.

If you add the route using router.add, which the proxy does you can route by path, method and headers. I should probably add something in the documentation about this..

The rule below will filter the request based on path, method, host, header and protocol:

const rules = [{
    handlerName: 'response',
    host: 'example.com',
    path: '/hello',
    protocol: 'http',
    headers: {
        'cf-ipcountry': 'es' 
    },
    options: {
      body: 'Hello world!',
  }];

As a sidenote you can also use this routing to make a https-redirect :)

{
    "handlerName": "response",
    "host": "example.com",
    "protocol": "http",
    "path": "/:file*",
    "options": {
      "status": 301,
      "body": "Redirecting to https",
      "headers": {
        "location": "https://example.com/{file}"
      }
    }
  },

Does this work for you or is there something we need to add?

danbars commented 4 years ago

Perfect! If you can update the documentation it would be great. Thanks!

danbars commented 4 years ago

BTW - not sure it's a best practice to redirect http to https with a path. The reason - it encourages clients to leave their code with http, without even realizing that the path is already sent unencrypted. e.g. http://api.myproduct.com/users/45434?token=876543 This will return the user's data, but a man in the middle will be able to get both the token and the userid...

markusahlstrand commented 4 years ago

Interesting.. haven't thought about it. Maybe need to check how others are doing it.