为了账号安全,请及时绑定邮箱和手机立即绑定

Go如何打开文件?

Go如何打开文件?

Go
侃侃无极 2022-08-01 17:34:21
我用Iris版本12构建了一个Go Web项目,现在有一个名为,我可以通过包含的文件夹中的shell脚本输出,但是去注意我。该文件夹的结构如下:config.goconfig.jsoncat ../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附言我还尝试了在shell中可用,在Go中不可用。./../config.json具体如下:config.gopackage configimport (    "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}
查看完整描述

2 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

相对路径始终相对于正在运行的进程的当前工作目录(不一定是可执行文件的目录)。它与原始源文件的位置无关。


要调试您的问题,您可以在尝试读取配置文件之前尝试打印出当前工作目录:


cwd, err := os.Getwd()

if err != nil {

    log.Fatal(err)

}

fmt.Println(cwd)

然后,给定的相对路径将添加到该路径中。os.Open()


如果您从存储库的根目录运行程序,那么配置的正确路径将很简单(除非您通过调用来更改代码中某个位置的工作目录)。os.Open("config.json")os.Chdir()


查看完整回答
反对 回复 2022-08-01
?
守着一只汪

TA贡献1872条经验 获得超4个赞

只需从文件路径中删除即可。如果您在项目目录的根目录中有文件 - 只需使用文件名即可从项目中的每个位置访问它。../

func InitConfig() *AppConfig {
    file, err := os.Open("config.json")
}

项目结构:

//img1.sycdn.imooc.com//62e79e4000015b2a01760153.jpg

结果:

//img1.sycdn.imooc.com//62e79e4b0001649003910047.jpg

main.go:


package main


import (

    "fmt"

    "scripts/playground/config"

)


func main() {

    cfg := config.InitConfig()

    fmt.Printf("%+v", cfg)

}



查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 246 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号