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

标签 go gorilla negroni

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

/static/876dsf5g87s6df5gs876df5g/application.js

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

/build/application.js

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

最佳答案

您是否已决定如何记录/保留 URL 的“随机”部分? D B?在内存中(即不跨重启)?如果不是,crypto/sha1 启动时的文件,并将生成的 SHA-1 哈希存储在映射/slice 中。

否则,像(假设是 gorilla )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 - 使用 Go/Negroni/Gorilla Mux 从静态 url 提供文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29441239/

相关文章:

csv - GoCSV : concatenate 2 csv columns into a single struct member

go - 跨包共享 gorilla/mux 路由器

html - 在 gorilla mux 中渲染 css js img 文件

go - axios 不发送 POST 到 golang api

go - 使用 Negroni 时自定义 HTTP 处理程序可以全局使用还是仅按请求使用?

go - 如何实现接口(interface),但发布新的API?

go - 解析 yaml 结构错误

hash - Go 中的 OpenPGP 错误 : "crypto: requested hash function is unavailable"

go - Websocket 发送到特定客户端而不是广播

go - negroni 中不同路由的不同中间件