使用 Go / Negroni / Gorilla Mux 从静态 url 提供文件

Serving files from static url with Go / Negroni / Gorilla Mux

所以我是 Go 的新手,正在尝试构建一个简单的 Web 服务器。我遇到问题的一部分是我想使用动态静态 urls 提供静态文件(以启用浏览器的长期缓存)。例如,我可能有这个 url:

/static/876dsf5g87s6df5gs876df5g/application.js

但我想提供位于以下位置的文件:

/build/application.js

我将如何使用 Go / Negroni / Gorilla Mux 来解决这个问题?

您是否已决定如何 record/persist URL 的 "random" 部分? D B?在内存中(即不跨重启)?如果不是,crypto/sha1 启动时的文件,并将生成的 SHA-1 哈希存储在 map/slice.

否则,像(假设是大猩猩)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 实现等中受益。

我知道为时已晚,但也许我的回答也会对其他人有所帮助。我找到了一个图书馆 go-staticfiles which implements static files caching and versioning by adding a hash to the file names. Thus it is possible to set long time cache for assets files and when they changes get fresh copy instantly. Also it is easy to implement template function to convert link to static file {{static "css/style.css"}} to a real path /static/css/style.d41d8cd98f00b204e9800998ecf8427e.css. Read more examples in README