Add ETag feature for cache plugin-assets

This commit is contained in:
KOUNOIKE
2019-01-06 18:26:17 +09:00
parent 5ce72e2056
commit 3c88fabab3
2 changed files with 33 additions and 18 deletions

View File

@@ -409,6 +409,13 @@ object PluginRegistry {
} }
} }
def getPluginInfoFromClassLoader(classLoader: ClassLoader): Option[PluginInfo] = {
instance
.getPlugins()
.find { info =>
info.classLoader.equals(classLoader)
}
}
} }
case class Link( case class Link(

View File

@@ -1,7 +1,6 @@
package gitbucket.core.servlet package gitbucket.core.servlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse} import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import gitbucket.core.plugin.PluginRegistry import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.util.FileUtil import gitbucket.core.util.FileUtil
import org.apache.commons.io.IOUtils import org.apache.commons.io.IOUtils
@@ -17,24 +16,33 @@ class PluginAssetsServlet extends HttpServlet {
assetsMappings assetsMappings
.find { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) } .find { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) }
.flatMap { .foreach {
case (prefix, resourcePath, classLoader) => case (prefix, resourcePath, classLoader) =>
val resourceName = path.substring(("/plugin-assets" + prefix).length) val ifNoneMatch = req.getHeader("If-None-Match")
Option(classLoader.getResourceAsStream(resourcePath.stripPrefix("/") + resourceName)) PluginRegistry.getPluginInfoFromClassLoader(classLoader).map { info =>
} val etag = s""""${info.pluginJar.lastModified}"""" // ETag must wrapped with double quote
.map { in => if (ifNoneMatch == etag) {
try { resp.setStatus(304)
val bytes = IOUtils.toByteArray(in) } else {
resp.setContentLength(bytes.length) val resourceName = path.substring(("/plugin-assets" + prefix).length)
resp.setContentType(FileUtil.getMimeType(path, bytes)) Option(classLoader.getResourceAsStream(resourcePath.stripPrefix("/") + resourceName))
resp.setHeader("Cache-Control", "max-age=3600") .map { in =>
resp.getOutputStream.write(bytes) try {
} finally { val bytes = IOUtils.toByteArray(in)
in.close() resp.setContentLength(bytes.length)
} resp.setContentType(FileUtil.getMimeType(path, bytes))
} //resp.setDateHeader("Last-Modified", lastModified)
.getOrElse { resp.setHeader("ETag", etag)
resp.setStatus(404) resp.getOutputStream.write(bytes)
} finally {
in.close()
}
}
.getOrElse {
resp.setStatus(404)
}
}
}
} }
} }