Problems encountered

Error: open./config/my.ini: no such file or directory

The error code is as follows:

conf, err := ini.Load(path + "./config/my.ini")
	iferr ! =nil {
		log.Fatal("Configuration file reading failed, err =", err)
}
Copy the code

Through analysis and data query, we know that the relative path of Golang is relative to the directory when the command is executed. Of course, they can’t read it

Analyze the problem

We focus on the output of go Run and discover that it is the address of a temporary file. Why?

In Go Help Run, we can see that

Run compiles and runs the main package comprising the named Go source files.
A Go source file is defined to be a file ending in a literal ".go" suffix.
Copy the code

/ TMP /go-build… Directory, compile and run

So go run main.go/TMP /go-build962610262/b001/exe is not surprising because it already runs to the temporary directory to execute the executable

So that’s pretty clear, so let’s think about what the problems are going to be

  • A file path error occurs when the file depends on the relative path
  • Go Run and Go Build are different. One run is executed in a temporary directory, while the other can be executed in a compiled directory
  • Keep going run, keep generating new temporary files

This is actually the root cause, because go Run and Go Build compile file execution path is different, the execution level may be different, naturally all kinds of strange problems can not read

The solution

To solve the problem of cross-directory execution of go build main.go executables (e.g../ SRC /gin-blog/main), splice the relative path of configuration files with the result of GetAppPath().

import (
    "path/filepath"
    "os"
    "os/exec"
    "string"
)

func GetAppPath(a) string {
    file, _ := exec.LookPath(os.Args[0])
    path, _ := filepath.Abs(file)
    index := strings.LastIndex(path, string(os.PathSeparator))

    return path[:index]
}
Copy the code

However, this method is still invalid for go run, and 2 is needed to remedy it

You can solve the go Run problem by passing parameters to specify a path

package main

import (
    "flag"
    "fmt"
)

func main(a) {
    var appPath string
    flag.StringVar(&appPath, "app-path"."app-path")
    flag.Parse()
    fmt.Printf("App path: %s", appPath)
}
Copy the code

run

go run main.go --app-path "Your project address"
Copy the code

The final code

file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
index := strings.LastIndex(path, string(os.PathSeparator))
path = path[:index]

conf, err := ini.Load(path + "/config/my.ini")
iferr ! =nil {
	log.Fatal("Configuration file reading failed, err =", err)
}
Copy the code

The relevant knowledge

Go language: How to solve the problem of reading the relative path configuration file

Golang “relative” path problem

Mac golang environment installation and beginners

Novice golang development notes

Personal learning repository: Occasionally submit learning code