go - http.StripPrefix : Serving a file from a custom folder

标签 go

我从这个目录运行 main.cgi:

htmlroot/sub/main.cgi

对资源的请求可能如下所示:

http://www.mysite/sub/main.cgi

我的 HTML 页面包含静态 CSS 文件,引用如下:

<link href="/styles/main.css" rel="stylesheet">

然而,静态文件实际上位于此处:

htmlroot/sub/styles/main.css

我试图告诉 Go 从 htmlroot/sub/styles 而不是 htmlroot/styles 获取文件,但我似乎无法让它工作。代码如下所示:

styleDir := http.FileServer(http.Dir("styles")) //I think this should point to root/sub/styles -- but maybe not?

http.Handle("/styles/", http.StripPrefix("/styles/", styleDir)

在这种情况下,找不到 main.css。我相信它实际上是在 htmlroot/styles 中寻找它,但我不确定为什么。

如果有任何提示,我将不胜感激。

最佳答案

试试这个:

styleDir := http.FileServer(http.Dir("sub"+filepath.Separator+"styles"))
http.Handle("/styles/", http.StripPrefix("/styles/", styleDir)

关于go - http.StripPrefix : Serving a file from a custom folder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48312056/

相关文章:

Golang Gin "c.Param undefined (type *gin.Context has no field or method Param)"

go - vscode-go 输入标签大小为 4 而不是 8

go - 声明递归/多维映射

file - golang 阅读更多 4096 字节

go - 如何分析多个 goroutine

regex - Golang 正则表达式无法匹配字节 10

go - 如何在 go text/template 中使用 .Key

go - 带有聚合和分组的 mgo

go - Redis 如何使用 golang 监听 1000 到 10,000 个列表的变化?

go - 在Go中将html字符串解析为模板