Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] DESCRIPTIVE TITLE #150

Open
cordmaker opened this issue Jun 28, 2024 · 0 comments
Open

[feat] DESCRIPTIVE TITLE #150

cordmaker opened this issue Jun 28, 2024 · 0 comments

Comments

@cordmaker
Copy link

cordmaker commented Jun 28, 2024

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) {
  // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant