背景
学习使用go语言和beego框架中的踩过的一些坑,记录下来以便交流。
1. JSON-to-Go工具
首先介绍一个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"`
}
2 go语言中的指针数据结构使用时要进行初始化,不然会报错
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{}
本文分享了在使用Go语言及Beego框架过程中遇到的问题及解决办法,包括如何利用JSON-to-Go工具将JSON文件自动转换为Go语言的结构体,并介绍了在使用指针数据结构时需要注意的初始化问题。
1023

被折叠的 条评论
为什么被折叠?



