dongsechuan0535 2017-03-21 12:35
浏览 52
已采纳

如何在Go应用程序中可靠地引用静态文件?

I am writing a Go command-line tool that generates some files based on templates.

The templates are located in the Git repository alongside the code for the command-line tool itself.

I wanted to allow the following:

  1. The binary, wherever it is called from, should always find the templates directory.
  2. The templates directory can be overriden by the user if need be.

Since this is a Go application, I went with something like:

templateRoot := filepath.Join(
    os.Getenv("GOPATH"),
    "src/github.com/myuser/myproject/templates",
)

But being rather new to Go, I wonder if this approach is reliable enough: is it guaranteed that my application template will always be accessible at that path ?

What if someone vendorize my application into their own project ? Does that even make sense for a command-line tool ?

Because of 2., I obviously can't/won't use go-bindata because I want to allow for the templates to be overriden if need be.

In summary: what is a good strategy to reliably refer to non-go, static files in a Go command-line tool ?

  • 写回答

1条回答 默认 最新

  • duandang2838 2017-03-21 13:33
    关注

    GOPATH is used for building the application. While you could look for GOPATH and check relative locations to each GOPATH entry at runtime, you can't be sure it will exist (unless of course you make it a prerequisite for running your application).

    go get itself is a convenience for developers to fetch and build a go package. It relies on having a GOPATH (though there's a default now in go1.8), and GOBIN in your PATH. Many programs require extra steps not covered by the simple go tool, and have scripts or Makefiles to do the build. If you're targeting users that aren't developers, you need to provide a way to install into standard system paths anyway.

    Do what any regular program would do, and use some well-known path to locate the template files. You can certainly add some logic in your program to check for a hierarchy of locations: relative to $GOPATH, relative to the binary, working directory, $HOME, etc; just provide a list of locations to the user that your program will look for templates.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错