Skip to content

[feat] DESCRIPTIVE TITLE #150

Open
Open
@cordmaker

Description

Hello, I am from China, my English is not very good, this article is translated by Google, please forgive me if you can't understand it.

Can you support negotiated cache? Automatically generate and add ETag and Last-Modified request headers, and process If-Modified-Since and If-None-Match request headers to implement this function, which meets the basic functions of a static resource server.

Currently I implement this function like this:

const Koa = require('koa')
const static = require('@koa/static') // koa-send is used internally

const app = new Koa()

let koaStaticMiddleware

app.use((ctx, next) => {
  if (!koaStaticMiddleware) {
    koaStaticMiddleware = static('./public', {
      setHeaders(res, path, stats) {
        const fileHash = getFileHash(path)
        res.setHeader('Cache-Control', 'no-cache')
        res.setHeader('ETag', fileHash)
        res.setHeader('Last-Modified', stats.mtime.toUTCString())

        const etag = ctx.headers['if-none-match']
        const lastModified = ctx.headers['if-modified-since']

        if (
          (etag && etag === fileHash) ||
          (lastModified && lastModified === stats.mtime.toUTCString())
        ) {
          ctx.throw(304, 'Not Modified')
        }
      }
    })
  }
  return koaStaticMiddleware(ctx, next)
})

function getFileHash(filePath) {
  // ...
}

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions