如何在连接路径时添加尾部斜杠

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

How to add a trailing slash when joining paths

问题

我正在制作一个 Web 应用程序,我试图编写 views/layouts/*.html,使用两个变量,但是 filepath.Join 只返回 views/layouts 而不是 views/layouts/

var (
	LayoutDir    string = filepath.Join("views", "layouts")
	TemplateExt  string = "*.html"
)

然后调用

f, err := filepath.Glob(LayoutDir + TemplateExt)

所以 f 包含的是 views/layouts*.html 而不是 views/layouts/*.html。我应该如何解决这个问题?在这种情况下使用 filepath.Join 是一个好的做法吗?

英文:

Im making a webapp and I'm trying to write views/layouts/*.html
using two vars but filepath.Join only gives views/layouts instead of views/layouts/

var (
	LayoutDir string = filepath.Join("views","layouts")
	TemplateExt string = "*.html"
)

then calling

f, err:= filepath.Glob(LayoutDir + TemplateExt)

And so f contains views/layouts*.html instead of views/layouts/*.html
How should I solve this and is it a good practice to use filepath.Join in this case?

答案1

得分: 4

f, err := filepath.Glob(filepath.Join(LayoutDir, TemplateExt))应该可以解决问题。

或者

LayoutDir string = filepath.Join("views", "layouts") + string(filepath.Separator)

或者

LayoutDir string = filepath.Join("views", "layouts") + string(os.PathSeparator)

英文:

f, err:= filepath.Glob(filepath.Join(LayoutDir, TemplateExt)) should do the trick

or

LayoutDir string = filepath.Join("views", "layouts") + string(filepath.Separator)

or

LayoutDir string = filepath.Join("views", "layouts") + string(os.PathSeparator)

答案2

得分: 1

我没有足够的声望来发表评论 - 也许管理员会将我的“答案”移动到评论中。一个需要注意的快速事项是,这段代码在Windows机器上会生成views/layouts\...我建议使用/代替filepath.Separatoros.PathSeparator

英文:

I don't have enough rep to comment - maybe a mod will move my 'answer' to a comment. One quick thing to beware of is this code will produce views/layouts\ on windows machines... I'd just use / instead of filepath.Separator or os.PathSeparator.

huangapple
  • 本文由 发表于 2022年4月24日 03:28:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/71982990.html
匿名

发表评论

匿名网友

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

确定