你已经决定如何记录/坚持URL的“随机”部分? D B?在内存中(即不在重新启动)?如果没有,则在启动时启动文件,并将生成的SHA-1散列存储在映射/片中。
否则,像(假设大猩猩)r.Handle("/static/{cache_id}/{filename}", YourFileHandler)
会工作的路线。
package main
import (
"log"
"mime"
"net/http"
"path/filepath"
"github.com/gorilla/mux"
)
func FileServer(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["cache_id"]
// Logging for the example
log.Println(id)
// Check if the id is valid, else 404, 301 to the new URL, etc - goes here!
// (this is where you'd look up the SHA-1 hash)
// Assuming it's valid
file := vars["filename"]
// Logging for the example
log.Println(file)
// Super simple. Doesn't set any cache headers, check existence, avoid race conditions, etc.
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(file)))
http.ServeFile(w, r, "/Users/matt/Desktop/"+file)
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello!\n"))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", IndexHandler)
r.HandleFunc("/static/{cache_id}/{filename}", FileServer)
log.Fatal(http.ListenAndServe(":4000", r))
}
这应该工作开箱即用,但我不能保证它的生产做好准备。就我个人而言,我只是使用nginx来服务我的静态文件,并从它的文件处理程序缓存,固体gzip实现等中受益,
这就是我一直在寻找的。我调整了路径路径,使其看起来像'myMux.HandleFunc(“/ static/{cache_id}/{filename:[a-zA-Z0-9 \\。\\ - \\ _ \\// *}}”, FileServer)',这样就可以处理像'/ static/8s7df65g87sd6f5g/app/test.html'这样的深层路径。我也同意在生产中,我会通过像nginx这样的服务来运行Go应用程序,它可以更好地处理这种类型的事情,但这个应用程序被设计成一个快速开发服务器(比Python的SimpleHTTPServer更好用) 。谢谢。 – ryanzec 2015-04-04 10:22:34