URL の「ランダム」部分を記録/保持する方法は既に決定していますか? DB? メモリ内 (つまり、再起動間ではない)? そうでない場合は、crypto/sha1起動時にファイルを取得し、結果の 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 実装などの恩恵を受けています。