Created
August 19, 2013 20:48
-
-
Save jcern/6274003 to your computer and use it in GitHub Desktop.
Avoiding JS and CSS Caching in a way that allows serving of non-lift resources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import net.liftweb.util.{NamedPF, Helpers} | |
import net.liftweb.http._ | |
import net.liftweb.http.RewriteRequest | |
import net.liftweb.http.ParsePath | |
import java.io.File._ | |
object CustomResourceId { | |
val suffixes = List("css", "js") | |
def init() : Unit = { | |
// The random number we're using to avoid caching | |
val resourceId = Helpers.nextFuncName | |
// Prefix with-resource-id links with "/cache/{resouceId}" | |
LiftRules.attachResourceId = (path: String) => { | |
val extension = (path.lastIndexOf("."), path.lastIndexOf("?")) match { | |
case (pos, pos2) if(pos2 > pos && pos > 0) => path.substring(pos + 1, pos2) | |
case (pos, pos2) if(pos > 0) => path.substring(pos + 1) | |
case _ => "" | |
} | |
if(suffixes.contains(extension)) { | |
"/cache/" + resourceId + path | |
} else { | |
path + (if (path contains ("?")) "&" else "?") + resourceId + "=_" | |
} | |
} | |
suffixes.foreach{ s => | |
LiftRules.statelessRewrite.prepend { | |
case RewriteRequest(ParsePath("cache" :: `resourceId` :: file, `s`, _, _), _, _) => { | |
RewriteResponse(file, s) | |
} | |
} | |
LiftRules.statelessDispatch.prepend { | |
case Req(`s` :: file :: Nil, `s`, _) => | |
() => for (in <- LiftRules.getResource(separator + s + separator + file + "." + s).map(_.openStream)) | |
yield { | |
StreamingResponse(in, () => in.close, size = -1, | |
headers = Nil, cookies = Nil, code=200) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment