douwen2072 2019-05-09 14:11
浏览 103
已采纳

即使设置了结构标签也无法解析TOML文件

I installed dependency using:

go get github.com/BurntSushi/toml

I created a toml file in the same folder as my main.go:

.
|-- cloud.toml
`-- main.go

cloud.toml

[database]
host = "localhost"
port = 8086
secure = false
username = "test"
password = "password"
dbName = "test"

main.go

package main

import (
    "fmt"
    "github.com/BurntSushi/toml"
)

type tomlConfig struct {
    DB dbInfo
}

type dbInfo struct {
    Host string `toml:"host"`
    Port int    `toml: "port"`
    Secure bool `toml: "secure"`
    Username string `toml: "username"`
    Password string `toml: "password"`
    DbName string `toml:"dbName"`
}

func main() {
    var dbConfig tomlConfig

    if _, err := toml.DecodeFile("cloud.toml", &dbConfig); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Database Configuration")
    fmt.Printf("Host: %s
", dbConfig.DB.Host)
    fmt.Printf("Port: %d
", dbConfig.DB.Port)


}

Output

go run main.go

Database Configuration
Host:
Port: 0

What am I doing wrong here?

my go env is:

set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\des\AppData\Local\go-build
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=C:\Users\des\go
set GOPROXY=
set GORACE=
set GOROOT=C:\Go
set GOTMPDIR=
set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\des\AppData\Local\Temp\go-build309995570=/tmp/go-build -gno-record-gcc-switches
  • 写回答

1条回答 默认 最新

  • duannaikuang1301 2019-05-09 14:15
    关注

    You need to add the appropriate toml tag to your struct:

    type tomlConfig struct {
         DB dbInfo `toml:"database"`
    }
    

    You should also remove the spaces from your other tags, to make them valid:

    type dbInfo struct {
        Host     string `toml:"host"`
        Port     int    `toml:"port"`
        Secure   bool   `toml:"secure"`
        Username string `toml:"username"`
        Password string `toml:"password"`
        DbName   string `toml:"dbName"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?