使用go.rice和http.ServeFile()。

huangapple go评论102阅读模式
英文:

Use go.rice with http.ServeFile()

问题

也许我在看错地方,但我找不到使用go.rice和http.ServeFile()的示例。基本上,我想要的是使用http.ServeFile()来提供一个打包的文件。目前我有以下代码。正如你所看到的,我正在寻找一种获取打包文件的字符串路径的方法,因为http.ServeFile需要这个路径。我不知道该怎么做。有什么建议吗?

var StaticBox *rice.Box

func NewStaticBox() {
    StaticBox = rice.MustFindBox("../../static")
}

func Static(req *http.Request, resp *http.Response) {
    stringToBoxedFile := 在这里该怎么做
    http.ServeFile(req, resp, stringToBoxedFile)
}

我可以以各种方式使用rice.box。我可以使用StaticBox.String()将文件内容作为字符串获取,等等。但现在我想要一个字符串作为打包文件的“路径”。

英文:

Maybe I'm looking at the wrong places, but I cannot find an example of using go.rice with http.ServeFile(). Basically what I want is serve a boxed file with http.ServeFile(). What I have now is the following. As you can see I'm looking for a way to get the string location of a boxed file, since http.ServeFile requires that. I don't know how to get it. Any suggestions?

var StaticBox *rice.Box

func NewStaticBox() {
	StaticBox = rice.MustFindBox("../../static")
}

func Static(req *http.Request, resp *http.Response) {
	stringToBoxedFile := WHAT-TO-DO-HERE
	http.ServeFile(req, resp, stringToBoxedFile)
}

I can use the rice.box in various ways. I can get a file contents as a string with StaticBox.String(), etc. But now I want a string as a "location" to a boxed file.

答案1

得分: 3

你可以使用http.ServeContent
获取一个HTTPBox,并使用HTTPBox.Open获取一个实现了io.ReadSeeker接口的http.File,然后可以将其与ServeContent一起使用。

另外,你也可以使用HTTPBox和http.FileServer,正如go.rice文档中所建议的那样(http.FileServer会获取请求的路径,并将其作为文件名在box中查找文件)。

英文:

You could use http.ServeContent instead.
Get a HTTPBox and use HTTPBox.Open to get a http.File, which implements io.ReadSeeker, so it can be used with ServeContent.

Alternatively, you could use HTTPBox with http.FileServer, as suggested in the documentation of go.rice (http.FileServer will get the path of the request, and use that as a filename to find the file in the box.)

答案2

得分: 2

实际上,有一个非常简单和简短的解决方案可以实现你想要的:

func main() {
    box := rice.MustFindBox("../../static")
    http.Handle("/", http.FileServer(box.HTTPBox()))
    http.ListenAndServe(":8080", nil)
}
英文:

There is actually a very simple and short solution to achieve what you want:

func main() {
 box := rice.MustFindBox("../../static")
 http.Handle("/", http.FileServer(box.HTTPBox()))
 http.ListenAndServe(":8080", nil)
}

huangapple
  • 本文由 发表于 2016年3月20日 17:33:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/36112133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定