Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

How does Go open files?

I built a Go Web Project with Iris version 12, and now there is a file named config.go, I can output config.json by shell script cat ../config.json in the folder which includes config.go, but Go note me that panic: open ../config.json: no such file or directory.
The structure of the folder is as following:

.
├── 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

P.S. I also tried ./../config.json which is available in shell and not available in Go.

The config.go was as following:

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
}

question from:https://stackoverflow.com/questions/65846236/how-does-go-open-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

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()).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...