你已經決定如何記錄/堅持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