在下面的代码中,我试图将变量“ Regprofile”作为全局变量访问,但输出为空。有帮助吗?
type GMLCInstance struct {
NfInstanceID string `json:"nfInstanceID"`
HeartBeatTimer int `json:"heartBeatTimer"`
NfType []string `json:"nfType"`
NfStatus []string `json:"nfStatus"`
Ipv4Addresses []string `json:"ipv4Addresses"`
}
var Regprofile GMLCInstance
// Request credentials and token from NRF and register profile to NFR database
func init() {
urlcred := "https://127.0.0.1:9090/credentials"
// Perform the request
resp, err := netClient.Get(urlcred)
if err != nil {
log.Fatalf("Failed get: %s", err)
}
defer resp.Body.Close()
// Fill the record with the data from the JSON
var cr Credential
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&cr); err != nil {
log.Println(err)
}
//fmt.Println(cr)
clientId := cr.CLIENTID
clientsec := cr.CLIENTSECRET
// Get token
reqtoken := url.Values{
"grant_type": []string{"client_credentials"},
"client_id": []string{clientId},
"client_secret": []string{clientsec},
"scope": []string{"GMLC"},
}
urlq := "https://127.0.0.1:9090/oauth2/token?"
res, err := netClient.PostForm(urlq+reqtoken.Encode(), nil)
if err != nil {
log.Fatalf("Failed get: %s", err)
}
var auth AccessToken
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(res.Body).Decode(&auth); err != nil {
log.Println(err)
}
//fmt.Println(auth.AccessToken)
token := auth.AccessToken
para := url.Values{
"access_token": []string{token},
}
//============================================================
// Register GMLC Instance to NRF, PUT
var gmlc = []byte(`{
"nfInstanceID": "f81d4fae-7dec-11d0-a765-00a0c91egmlc",
"heartBeatTimer": 0,
"nfType": ["GMLC"],
"nfStatus": ["string"],
"ipv4Addresses": ["172.16.0.X:5000"]
}`)
//================= Registser profile to NRF ========================//
postnrf := "https://127.0.0.1:9090/nnrf-nfm/v1/nf-instances/f81d4fae-7dec-11d0-a765-00a0c91egmlc?"
rq, err := http.NewRequest("PUT", postnrf+para.Encode(), bytes.NewBuffer(gmlc))
rq.Header.Set("Content-Type", "application/json")
rq.Header.Set("Accept", "application/json")
response, err := netClient.Do(rq)
if err != nil {
panic(err)
}
defer res.Body.Close()
decoder := json.NewDecoder(response.Body)
var Regprofile GMLCInstance
err = decoder.Decode(&Regprofile)
if err != nil {
fmt.Println("Response body not well decoded")
}
fmt.Println(Regprofile)
}
fmt.Println(Regprofile)的输出给出 {f81d4fae-7dec-11d0-a765-00a0c91egmlc 10 [GMLC] [注册] [172.16.0.X:5000]}
但是,当我在main中将变量打印为
时func main(){
fmt.Println(Regprofile)
}
我得到空数据 {0 [] [] []}
答案 0 :(得分:1)
在func init()
中,您在本地将变量var Regprofile GMLCInstance
重新声明为函数作用域。该声明用局部变量遮盖了全局变量。只需在init()
中删除此本地声明即可。