Serve Compressed Javascript

agolangf · · 584 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 &#34;304 Not Modified&#34; if the client already has the current version of the code. </p> <pre><code>codeFiles := []string{&#34;code1.js&#34;, &#34;code2.js&#34;, &#34;code3.js&#34;} fileOut, _ := os.Create(&#34;codejs.gzip&#34;) 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(&#34;codejs.gzip&#34;) defer codeFile.Close() // url does not have to match actual file name, in html use &lt;script src=&#34;code.js&#34; ... http.HandleFunc(&#34;/code.js&#34;, func(w http.ResponseWriter, r *http.Request) { w.Header().Set(&#34;Content-Type&#34;, &#34;application/javascript&#34;) w.Header().Set(&#34;Content-Encoding&#34;, &#34;gzip&#34;) http.ServeContent(w, r, &#34;&#34;, modTime, codeFile) }) http.ListenAndServe(&#34;:http&#34;, nil) </code></pre> <hr/>**评论:**<br/><br/>BitWarrior: <pre><p>Being that <code>modTime</code> is being set on execution, wouldn&#39;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&#39;ll have to get the details on how to get the md5 value.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

584 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传