读取json配置

a.json

{
    "server":"aaa",
    "port":8000
}

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

type conf struct {
    Addr string `json:"serVer"` //注意想要拿到字段,字段和tag strings.EqualFold 之后至少有一个需和json里面的字段名一致
    Port int    `josn:"port"`
}

func main() {
    f, err := os.Open("./a.json")
    if err != nil {
        fmt.Printf("Open configuration error: %s\n", err)
        return
    }
    defer f.Close()
    configuration := &conf{}
    decoder := json.NewDecoder(f)
    err = decoder.Decode(configuration)
    if err != nil {
        panic(err)
    }
    fmt.Println(configuration.Addr, configuration.Port)
}

results matching ""

    No results matching ""