狂欢框架中的相对路径

Relative paths in revel framework

如何在revel 框架中将文件realive 导入到revel basefolder 中。目前我执行以下操作来获取一些配置值。

file, err := ioutil.ReadFile("conf/config.conf")
...

这导致我的服务器只有在我开始陶醉于

时站在应用程序目录中才能工作
revel run myapp

有没有办法访问基本文件夹?

revel包中有导出的全局变量,你可以使用其中的任何一个:

var (
    // App details
    AppName    string // e.g. "sample"
    BasePath   string // e.g. "/Users/revel/gocode/src/corp/sample"
    AppPath    string // e.g. "/Users/revel/gocode/src/corp/sample/app"
    ViewsPath  string // e.g. "/Users/revel/gocode/src/corp/sample/app/views"
    ImportPath string // e.g. "corp/sample"
    SourcePath string // e.g. "/Users/revel/gocode/src"

    // Revel installation details
    RevelPath string // e.g. "/Users/revel/gocode/src/revel"

    // Where to look for templates and configuration.
    // Ordered by priority.  (Earlier paths take precedence over later paths.)
    CodePaths     []string
    ConfPaths     []string
    TemplatePaths []string
)

如果它对您来说是空的,那很可能是因为您从基础文件夹启动了您的应用程序。

请注意,这些路径由 Init(mode, importPath, srcPath string) 函数设置。它的文档说明:

srcPath - the path to the source directory, containing Revel and the app.
  If not specified (""), then a functioning Go installation is required.

另请查看:how to reference a relative file from code and tests

我用这个方法: 在conf/app.conf中添加一行这样的配置路径:

projectname.path = "/文件夹名称/"

并在controller中写一个这样的方法:

func info(field string) string {                                                                                                                                                                               
  config, err := revel.LoadConfig("app.conf")                                                                                                                                                                  
  if err != nil || config == nil {                                                                                                                                                                             
    log.Fatalln("Failed to load configuration file", err)                                                                                                                                                      
   }                                                                                                                                                                                                            
  return config.StringDefault(field, "empty")                                                                                                                                                                  
} 

您可以使用此代码构建一个助手,并从所有应用程序中获取配置变量。

必须这样调用:

info("projectname.path")