<p>If your client side web app has lots of javascript files, here is the basic code to serve them as a single compressed file. For testing, include links for each js file (in index.html), then for production comment out those lines and include 1 line for the merged/compressed js file. This method will also return a "304 Not Modified" if the client already has the current version of the code. </p>
<pre><code>codeFiles := []string{"code1.js", "code2.js", "code3.js"}
fileOut, _ := os.Create("codejs.gzip")
compressor := gzip.NewWriter(fileOut)
for _, file := range codeFiles {
fileIn, _ := os.Open(file)
io.Copy(compressor, fileIn)
fileIn.Close()
}
compressor.Close()
fileOut.Close()
modTime := time.Now()
codeFile, _ := os.Open("codejs.gzip")
defer codeFile.Close()
// url does not have to match actual file name, in html use <script src="code.js" ...
http.HandleFunc("/code.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
w.Header().Set("Content-Encoding", "gzip")
http.ServeContent(w, r, "", modTime, codeFile)
})
http.ListenAndServe(":http", nil)
</code></pre>
<hr/>**评论:**<br/><br/>BitWarrior: <pre><p>Being that <code>modTime</code> is being set on execution, wouldn't the mod time always return the current time, thus the client always will request a new file?</p></pre>jayposs: <pre><p>No, modTime is set when the app loads. Typically the app will run for a long time (like weeks). Of course you can use some other logic for setting this value.</p></pre>BitWarrior: <pre><p>You have the opportunity to take the md5 value of your concatenated file and produce an etag out of it. You would get more accurate and potentially longer lived caching out of the deal.</p></pre>jayposs: <pre><p>Sounds like a good idea. I'll have to get the details on how to get the md5 value.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传