doujiu3768 2015-04-03 23:53
浏览 37
已采纳

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

So I am new to Go and trying it out to build a simple web server. One part I am having trouble with is that I want to serve static files with dynamic static urls (to enable long caching by the browser). For example, I might have this url:

/static/876dsf5g87s6df5gs876df5g/application.js

But I want to serve the file located at:

/build/application.js

How would I go about this with Go / Negroni / Gorilla Mux?

  • 写回答

2条回答 默认 最新

  • dsg41888 2015-04-04 06:39
    关注

    Have you already decided on how to record/persist the "random" part of the URL? DB? In memory (i.e. not across restarts)? If not, crypto/sha1 the file(s) on start-up, and store the resultant SHA-1 hash in a map/slice.

    Otherwise, a route like (assuming Gorilla) r.Handle("/static/{cache_id}/{filename}", YourFileHandler) would work.

    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!
    "))
    }
    
    func main() {
    
        r := mux.NewRouter()
    
        r.HandleFunc("/", IndexHandler)
        r.HandleFunc("/static/{cache_id}/{filename}", FileServer)
    
        log.Fatal(http.ListenAndServe(":4000", r))
    }
    

    That should work out of the box, but I can't promise it's production ready. Personally, I just use nginx to serve my static files and benefit from it's file handler cache, solid gzip implementation, etc, etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化