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(

View File

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