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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度