dougu1985 2012-12-16 18:52
浏览 73
已采纳

在Go程序中捆绑静态资源的最佳方法是什么? [关闭]

I'm working on a small web application in Go that's meant to be used as a tool on a developer's machine to help debug their applications/web services. The interface to the program is a web page which includes not only the HTML, but some JavaScript (for functionality), images and CSS (for styling). I'm planning on open-sourcing this application, so users should simply be able to run a Makefile and all the resources will go where they need to go. However, I'd also like to be able to simply distribute an executable with as few files/dependencies as possible. Is there a good way to bundle the HTML/CSS/JS with the executable, so users only have to download and worry about one file?


Right now, in my app, serving a static file looks a little like this:

// called via http.ListenAndServe
func switchboard(w http.ResponseWriter, r *http.Request) {

    // snipped dynamic routing...

    // look for static resource
    uri := r.URL.RequestURI()
    if fp, err := os.Open("static" + uri); err == nil {
        defer fp.Close()
        staticHandler(w, r, fp)
        return
    }

    // snipped blackhole route
}

So it's pretty simple: if the requested file exists in my static directory, invoke the handler, which simply opens the file and tries to set a good Content-Type before serving. My thought was that there's no reason this needs to be based on the real filesystem: if there were compiled resources, I could simply index them by the request URI and serve them as such.

If there's not a good way to do this, or I'm barking up the wrong tree by trying to do this, let me know. I just figured the end-user would appreciate as few files as possible to manage.

If there are more appropriate tags than go, please feel free to add them or let me know.

  • 写回答

4条回答 默认 最新

  • dsfsda121545 2012-12-16 19:01
    关注

    The go-bindata package looks like it might be what you're interested in.

    https://github.com/go-bindata/go-bindata

    It will allow you to convert any static file into a function call that can be embedded in your code and will return a byte slice of the file content when called.

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?