项目结构如下:
```
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}}
```
请问是否有人知道是什么原因?
更多评论