0

だから、私はGoが初めてで、単純なWebサーバーを構築するために試しています。私が問題を抱えている部分の1つは、静的ファイルを動的静的URLで提供したいということです(ブラウザによる長いキャッシュを有効にするため)。たとえば、次の URL があるとします。

/static/876dsf5g87s6df5gs876df5g/application.js

しかし、次の場所にあるファイルを提供したい:

/build/application.js

Go / Negroni / Gorilla Mux でこれを行うにはどうすればよいですか?

4

2 に答える 2

4

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 実装などの恩恵を受けています。

于 2015-04-04T06:39:44.143 に答える