请教一个包导入问题,百思不得解!!!

weixin_38093910 2019-09-20 09:57:16
项目结构如下:
```
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}}
```
请问是否有人知道是什么原因?
...全文
26 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复

473

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧