go - How to get filepath relative to imported package's path? -


the problem can't reach file relative package path actual used. let's consider example. have following structure:

~/go/src/github.com/user/dbms   data/     database.db   dbms.go  ~/projects/myproj/bin   main.go 

dbms.go:

package dbms  import (   "os"   "fmt"   "path/filepath" )  type dbms struct {   filepath string }  func new() *dbms {   return &dbms{filepath: "./data/database.db"} }  func (d *dbms) run() {   fmt.println(filepath.abs(d.path))   // output: /home/timur/projects/myproj/bin/data   // need: /home/timur/go/src/github.com/user/dbms/data   file, err := os.openfile(d.filepath, os.o_rdwr, 0666)   // error } 

main.go:

package main  import (   "github.com/user/dbms" )  func main() {   db := dbms.new()   db.run() } 

as can see dbms.path resolves path relative entry point , not package itself. wrong?

the issue database file not part of compiled binary. seems expecting packaged binary when run code.

i think should reconsider approach. source code compiled static binary ran, binary not include database file. going have bad time trying guess correct path reliably.

i move path database file configuration param, either in config file required in current working directory @ runtime, or environment variable. then, pull database file out of package directory, since won't helping being there.

as far getting file @ runtime, add setup function scaffold database appropriate. or, if expecting preloaded data in database, ship in package final binary , config file.

hope helps!


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -