fvsch / servitsy

Small, local HTTP server for static files
MIT License
3 stars 0 forks source link

Feature: allow setting custom headers for responses #2

Closed fvsch closed 2 months ago

fvsch commented 2 months ago

Feature request: https://x.com/hsablonniere/status/1821475701532377471

Prior art:

  1. The node-static package has a --headers option which accepts a JSON string:
static --headers='{"Cache-Control": "no-cache, must-revalidate"}'
  1. The serve package supports a serve.json configuration files which can define headers with conditions to match specific files:
{
  "headers": [
    {
      "source" : "**/*.@(jpg|jpeg|gif|png)",
      "headers" : [{
        "key" : "Cache-Control",
        "value" : "max-age=7200"
      }]
    }, {
      "source" : "404.html",
      "headers" : [{
        "key" : "Cache-Control",
        "value" : "max-age=300"
      }]
    }
  ]
}
fvsch commented 2 months ago

A possible design would be to add a --header option accepting this format:

servitsy --header '[file_pattern] json_object'
servitsy --header '*.html {"set-cookie": "analytics_consent=0"}'
servitsy --header '{"set-cookie": "analytics_consent=0"}'

and perhaps a shorthand for a single header applying to all files:

servitsy --header 'key:value'
servitsy --header 'set-cookie:analytics_consent=0'

On the JS side, maybe an array like serve does, but not as verbose:

start({
  header: [
    {
      include: '*',
      headers: {'cache-control': 'max-age=300'}
    },
    {
      include: '*.html',
      headers: {'set-cookie': 'analytics_consent=0'}
    }
  ]
})
fvsch commented 2 months ago

Implemented in https://github.com/fvsch/servitsy/commit/b9550dcce9ee2d85d990945133621dbf32fec759