map[interface {}]interface {} yaml文件解码 检查类型断言
解析json、yaml文件
DsnDG : user:pwd@tcp(ip:portr)/db?charset=utf8mb4
type MysqlConfig struct {
DsnDG string `yaml:"DsnDG"`
}
// config should be a pointer to structure, if not, panic
func loadJsonConfig() *MysqlConfig {
workPath, err := os.Getwd()
if err != nil {
panic(err)
}
configPath := filepath.Join(workPath, "conf")
log.Println("configPath: ", configPath)
fullPath := filepath.Join(configPath, "db.yaml")
log.Println(fullPath)
file, err := os.Open(fullPath)
if err != nil {
msg := fmt.Sprintf("Can not load config at %s. Error: %v", fullPath, err)
panic(msg)
}
defer file.Close()
var bs []byte
bs, err = os.ReadFile(fullPath)
if err != nil {
panic(err)
}
config := &MysqlConfig{}
err = yaml.Unmarshal(bs, &config)
if err != nil {
panic(err)
}
return config
}
{
"topic":"a2",
"group.id":"go_dev",
"bootstrap.servers":"alikafka-pre-cn-st21wg28xxxx-1-vpc.alikafka.aliyuncs.com:9094,alikafka-pre-cn-st21wg28xxxx-2-vpc.alikafka.aliyuncs.com:9094,alikafka-pre-cn-st21wg28xxxx-3-vpc.alikafka.aliyuncs.com:9094",
"security.protocol":"sasl_plaintext",
"sasl.mechanism":"PLAIN",
"sasl.username":"SASL_PLAINTEXT_dg_go",
"sasl.password":"xxxxF$184354D20%A7F1Bent_de5F6A*301DF2D7"
}
type KafkaConfig struct {
Topic string `json:"topic"`
GroupId string `json:"group.id"`
BootstrapServers string `json:"bootstrap.servers"`
SecurityProtocol string `json:"security.protocol"`
SaslMechanism string `json:"sasl.mechanism"`
SaslUsername string `json:"sasl.username"`
SaslPassword string `json:"sasl.password"`
}
// config should be a pointer to structure, if not, panic
func loadJsonConfig() *KafkaConfig {
workPath, err := os.Getwd()
if err != nil {
panic(err)
}
configPath := filepath.Join(workPath, "conf")
log.Println("configPath: ", configPath)
fullPath := filepath.Join(configPath, "kafka.json")
file, err := os.Open(fullPath)
if err != nil {
msg := fmt.Sprintf("Can not load config at %s. Error: %v", fullPath, err)
panic(msg)
}
defer file.Close()
decoder := json.NewDecoder(file)
var config = &KafkaConfig{}
err = decoder.Decode(config)
if err != nil {
msg := fmt.Sprintf("Decode json fail for config file at %s. Error: %v", fullPath, err)
panic(msg)
}
json.Marshal(config)
return config
}
map[interface {}]interface {}
map[interface{}]interface{} on a map[string]interface{} · Issue #139 · go-yaml/yaml https://github.com/go-yaml/yaml/issues/139
f1: hi世界
f2:
f3: value
f4: [42, 1024]
f5: [a b]
f6:
f7: 77
f8: ok
package main
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v3"
)
func main() {
var err error
m := make(map[string]interface{})
var bs []byte
bs, err = ioutil.ReadFile("a.yaml")
if err != nil {
panic(err)
}
err = yaml.Unmarshal(bs, &m)
if err != nil {
panic(err)
}
f1v := m["f1"].(string)
var f3v string
var f4v []int
var f5v []string
var f6v map[string]interface{}
for k, v := range m["f2"].(map[string]interface{}) {
switch k {
case "f3":
f3v = v.(string)
case "f4", "f5":
l := v.([]interface{})
if k == "f4" {
for _, u := range l {
f4v = append(f4v, u.(int))
}
}
if k == "f5" {
for _, u := range l {
f5v = append(f5v, u.(string))
}
}
case "f6":
f6v = v.(map[string]interface{})
default:
}
}
fmt.Println("---->", f1v, f3v, f4v, f5v, f6v)
}
go run *go
----> hi世界 value [42 1024] [a b] map[f7:77 f8:ok]
2)
the-way-to-go_ZH_CN/11.3.md at master · unknwon/the-way-to-go_ZH_CN · GitHub https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/11.3.md
通常我们可以使用 类型断言 来测试在某个时刻 varI 是否包含类型 T 的值:
v := varI.(T) // unchecked type assertion
varI 必须是一个接口变量,否则编译器会报错:invalid type assertion: varI.(T) (non-interface type (type of varI) on left) 。
类型断言可能是无效的,虽然编译器会尽力检查转换是否有效,但是它不可能预见所有的可能性。如果转换在程序运行时失败会导致错误发生。更安全的方式是使用以下形式来进行类型断言:
if v, ok := varI.(T); ok { // checked type assertion
Process(v)
return
}
// varI is not of type T
如果转换合法,v 是 varI 转换到类型 T 的值,ok 会是 true;否则 v 是类型 T 的零值,ok 是 false,也没有运行时错误发生。
应该总是使用上面的方式来进行类型断言。
多数情况下,我们可能只是想在 if 中测试一下 ok 的值,此时使用以下的方法会是最方便的:
if _, ok := varI.(T); ok {
// ...
}

浙公网安备 33010602011771号