项目结构如下:
```
decoder
├── config.json
└── decoder.go
```
config.json 文件内容
```
{
"ServerInfo": {
"Host": "127.0.0.1:8888"
},
"RedisInfo": {
"Host": "127.0.0.1:6379",
"MaxIdle": 16,
"MaxActive": 0,
"IdleTimeout": 300
}
}
```
decoder.go 文件内容
```
package main
import (
"encoding/json"
"fmt"
"os"
"time"
)
type Config struct{}
type ConfigurationType struct {
ServerInfo ServerInfoType
RedisInfo RedisInfoType
}
type ServerInfoType struct {
Host string
}
type RedisInfoType struct {
Host string
MaxIdle int
MaxActive int
IdleTimeout time.Duration
}
var Configuration = ConfigurationType{}
func (this Config) InitConfig() {
file, _ := os.Open("config.json")
defer file.Close()
decoder := json.NewDecoder(file)
Configuration = ConfigurationType{}
err := decoder.Decode(&Configuration)
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Printf("Configuration: %v\n", Configuration)
}
func main() {
conf := Config{}
conf.InitConfig()
}
```
这种情况下我运行:`go run decoder.go` , 输出结果如下:
```
Configuration: {{127.0.0.1:8888} {127.0.0.1:6379 16 0 300ns}}
```
但是我把这个 main 包改为 decoder 包,项目结构调整如下
```
.
├── decoder
│ ├── config.json
│ └── decoder.go
└── main.go
```
config.json 文件内容
```
{
"ServerInfo": {
"Host": "127.0.0.1:8888"
},
"RedisInfo": {
"Host": "127.0.0.1:6379",
"MaxIdle": 16,
"MaxActive": 0,
"IdleTimeout": 300
}
}
```
decoder.go 文件内容
```
package decoder
import (
"encoding/json"
"fmt"
"os"
"time"
)
type Config struct{}
type ConfigurationType struct {
ServerInfo ServerInfoType
RedisInfo RedisInfoType
}
type ServerInfoType struct {
Host string
}
type RedisInfoType struct {
Host string
MaxIdle int
MaxActive int
IdleTimeout time.Duration
}
var Configuration = ConfigurationType{}
func (this Config) InitConfig() {
file, _ := os.Open("config.json")
defer file.Close()
decoder := json.NewDecoder(file)
Configuration = ConfigurationType{}
err := decoder.Decode(&Configuration)
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Printf("Configuration: %v\n", Configuration)
}
```
main.go 文件内容
```
package main
import "initTest/decoder"
func main() {
t := decoder.Config{}
t.InitConfig()
}
```
测试运行 `go run main.go` 报错如下:
```
Error: invalid argument
Configuration: {{} { 0 0 0s}}
```
请问是否有人知道是什么原因?
是文件路径问题。目前用的语言中,读取文件的相关函数,在文件路径错误的时候直接会抛异常,Golang 这种包底层直接返回 err 的做法还是又点儿不习惯,导致排查文件,压根没有想到是文件路径错误。
```
.....
func (this Config) InitConfig() {
file, err := os.Open("./config.json")
defer file.Close()
if err != nil {
fmt.Printf("Open file error: %v\n", err)
}
decoder := json.NewDecoder(file)
Configuration = ConfigurationType{}
err = decoder.Decode(&Configuration)
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Printf("Configuration: %v\n", Configuration)
}
```
打印了相关 Error,发现了是文件不存在。
#4
更多评论