学习使用go语言和beego框架中的踩过的一些坑,记录下来以便交流。
首先介绍一个json文件自动转化为go的数据结构的工具 JSON-to-Go
比如 prometheus server端查询出的一个结果的数据结构:
[
{
"metric":{
"__name__":"up",
"job":"prometheus",
"instance":"localhost:9090"
},
"value":[
1435781451.781,
"1"
]
},
{
"metric":{
"__name__":"up",
"job":"node",
"instance":"localhost:9100"
},
"value":[
1435781451.781,
"0"
]
}
]
通过这个工具可以转换为go语言中的struct结构:
type AutoGenerated []struct {
Metric struct {
Name string `json:"__name__"`
Job string `json:"job"`
Instance string `json:"instance"`
} `json:"metric"`
Value []interface{} `json:"value"`
}
Handler crashed with error runtime error: invalid memory address or nil pointer dereference 等错误
比如定义一个Result的数据结构:
type Result struct {
Metric Metric `json:"metric"`
Value []*Value `json:"value"`
}
type Metric struct {
Name string `json:"__name__"`
Job string `json:"job"`
Instance string `json:"instance"`
}
type Value interface{}
如果使用[]*Result切片时,要使用make方式进行初始化:
var results = make([]*Result,0)
使用*Result指针类型时,可以进行赋初值来初始化:
var result = &Result{}