Go 如何打开文件?

-2 go

我使用 Iris 版本 12 构建了一个 Go Web 项目,现在有一个名为 的文件config.go,我可以在包含 的文件夹中config.json通过 shell 脚本输出,但是请注意. 文件夹的结构如下:cat ../config.jsonconfig.gopanic: open ../config.json: no such file or directory

.
??? config
?   ??? config.go
??? config.json
??? config.yml
??? controller
??? datasource
??? go.mod
??? go.sum
??? main.go
??? model
?   ??? user.go
??? service
??? static
?   ??? css
?   ?   ??? app.85873a69abe58e3fc37a13d571ef59e2.css
?   ??? favicons
?   ?   ??? favicon.ico
?   ??? fonts
?   ?   ??? element-icons.b02bdc1.ttf
?   ??? img
?   ?   ??? default.jpg
?   ??? index.html
?   ??? js
?       ??? 0.6e924665f4f8679a8f0b.js
??? util
Run Code Online (Sandbox Code Playgroud)

PS我也试过./../config.json这是可以在外壳和不可用在围棋。

config.go是如下:

package config

import (
    "encoding/json"
    "os"
)

type AppConfig struct {
    AppName    string `json:"app_name"`    // Project name
    Port       int    `json:"port"`        // Server port
    StaticPath string `json:"static_path"` // The path of static resources
    Mode       string `json:"mode"`        // Development mode
}

func InitConfig() *AppConfig {
    file, err := os.Open("../config.json")
    if err != nil {
        panic(err.Error())
    }

    decoder := json.NewDecoder(file)
    conf := AppConfig{}
    err = decoder.Decode(&conf)
    if err != nil {
        panic(err.Error())
    }

    return &conf
}

Run Code Online (Sandbox Code Playgroud)

bla*_*ami 7

Relative path is always relative to the current working directory of the running process (which necessarily doesn't have to be a directory where the executable is). It has nothing to do with where original source file is.

To debug your issue you can try print out the current working directory just before you try to read the config file:

cwd, err := os.Getwd()
if err != nil {
    log.Fatal(err)
}
fmt.Println(cwd)
Run Code Online (Sandbox Code Playgroud)

Relative path given to os.Open() is then added to that path.

If you run your program from the root of repository then the proper path to config will be simply os.Open("config.json") (unless you change working directory somewhere in code by calling os.Chdir()).