preinit.go 881 B

1234567891011121314151617181920212223242526272829303132
  1. // Package preinit performs os.Chdir to the executable's directory before any
  2. // other package (including beego) initialises. This prevents beego's config
  3. // init() from printing a spurious "open conf/app.conf: no such file" debug
  4. // message when the binary is launched from a directory other than its own.
  5. //
  6. // Import this package as the very first blank import in main.go:
  7. //
  8. // _ "github.com/mindoc-org/mindoc/internal/preinit"
  9. package preinit
  10. import (
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. )
  15. func init() {
  16. exe, err := os.Executable()
  17. if err != nil {
  18. return
  19. }
  20. exeDir := filepath.Dir(exe)
  21. // Skip go-run temporary build directories.
  22. if strings.Contains(exeDir, "go-build") {
  23. return
  24. }
  25. // Only chdir when conf/app.conf actually exists next to the binary.
  26. if _, err := os.Stat(filepath.Join(exeDir, "conf", "app.conf")); err != nil {
  27. return
  28. }
  29. _ = os.Chdir(exeDir)
  30. }