douye9822 2016-03-26 17:05
浏览 36

如何获取当前文件的位置

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条回答 默认 最新

  • doulao5916 2016-03-26 19:38
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b