英文:
how to get the location of the current file in revel
问题
我正在使用golang revel web框架,并尝试在当前工作目录中创建一个sqlite
数据库。
model.go
func New(dbName string, table string) *Db {
_, filename, _, _ := runtime.Caller(1)
db, err := sql.Open("sqlite3", path.Join(path.Dir(filename), dbName))
if err != nil {
log.Fatal(err)
}
err = db.Ping()
if err != nil {
log.Panic(err)
}
database := &Db{Database: db}
_, err = db.Exec("create table %s" +
"( id integer primary key, " +
"name varchar(100)," +
"email varchar(100)," +
"branch varchar(100)," +
"help varchar(100))")
if err != nil {
log.Fatal(err)
}
}
我已经编写了一个测试,只是调用了这个函数。
每当我使用revel test
运行测试,或者通过访问localhost:9000/@tests
运行测试时,函数会引发Panic
,并显示错误消息无法打开数据库文件
。
发生这种情况的原因是runtime.Caller(1)
返回的filename
是/usr/local/go/src/runtime/asm_amd64.s
,程序对其没有权限。
即使我直接写入./foo.db
,错误仍然显示。
我尝试了os.Getwd()
,它返回空字符串。
我还尝试了filepath.Abs(filepath.Dir(os.Args[0]))
,但它返回的是/home/girish/GoProjects/bin/revel.d
,这是revel
二进制文件的位置。
那么找到model.go
所在目录的最佳方法是什么?
英文:
I am using golang revel web framework and
I am trying to create a sqlite
db in the current working directory.
model.go
func New(dbName string,table string) *Db {
_,filename,_,_ := runtime.Caller(1)
db , err := sql.Open("sqlite3",path.Join(path.Dir(filename),dbName))
if err != nil {
log.Fatal(err)
}
err = db.Ping()
if err != nil {
log.Panic(err)
}
database := &Db{Database:db}
_,err = db.Exec("create table %s" +
"( id integer primary key, " +
"name varchar(100),"+
"email varchar(100),"+
"branch varchar(100),"+
"help varchar(100)",)
if err != nil {
log.Fatal(err)
}
}
I have a test in place which just calls this function.
whenever i run the test using revel test
or by going to the localhost:9000/@tests
, the function Panics
and the error message is
cannot open the database file
.
The reason that is happening is because the filename
returned by runtime.Caller(1)
is /usr/local/go/src/runtime/asm_amd64.s
for which the program has no permission.
if i directly write ./foo.db
, even then the error shows.
I tried os.Getwd()
which return empty string.
I also tried filepath.Abs(filepath.Dir(os.Args[0]))
but that returned /home/girish/GoProjects/bin/revel.d
which is the revel
binary.
So whats the best way to find the directory of the model.go
?
答案1
得分: 1
在运行时获取model.go文件的目录并没有意义,因为编译后的可执行文件可能位于完全不同的文件系统上。
您可能想要获取正在运行的可执行文件的目录:
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
dir将是程序在运行时所在的文件夹。
英文:
It doesn't make sense to get the directory of the model.go file at runtime, because the compiled executable could be on a completely different filesystem.
You may want to get the directory of where the running executable was started from:
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
dir will be the folder where the program lives at runtime.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论