在 Go 程序中捆绑静态资源的最佳方法是什么? [英] What's the best way to bundle static resources in a Go program?

查看:26
本文介绍了在 Go 程序中捆绑静态资源的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Go 开发一个小型网络应用程序,该应用程序旨在用作开发人员机器上的工具,以帮助调试他们的应用程序/网络服务.该程序的界面是一个网页,它不仅包括 HTML,还包括一些 JavaScript(用于功能)、图像和 CSS(用于样式).我打算开源这个应用程序,所以用户应该能够简单地运行一个 Makefile,所有的资源都会去他们需要去的地方.但是,我还希望能够简单地分发具有尽可能少的文件/依赖项的可执行文件.有没有什么好办法将 HTML/CSS/JS 与可执行文件捆绑在一起,让用户只需要下载一个文件就可以了?

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
}

所以这很简单:如果请求的文件存在于我的静态目录中,则调用处理程序,它只是打开文件并尝试在服务之前设置一个好的 Content-Type.我的想法是没有理由这需要基于真实的文件系统:如果有已编译的资源,我可以简单地通过请求 URI 为它们编制索引,并为它们提供服务.

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.

推荐答案

go-bindata 包看起来可能正是您感兴趣的内容.

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.

这篇关于在 Go 程序中捆绑静态资源的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆