如何使用golang

时间:2017-12-04 20:48:02

标签: go ibm-cloud-infrastructure

func getPrivateVlan(env string) (string, error) {
// 1. Create a session
sess := session.New(user, pass)
// 2. Get a service
accountService := services.GetAccountService(sess)
// 3. Invoke a method:
vlans, err := accountService.GetNetworkVlans()
vlan := vlans[0]
log.Println(*vlan.Name)           //works
log.Println(*vlan.PrimaryRouter)  //Doesn't work
}

返回的对象是SoftLayer_Network_Vlan类型https://sldn.softlayer.com/reference/datatypes/softlayer_network_vlan的vlan类型数组。 我能够访问列"本地属性"中的属性。 (即名称)但我无法访问列中的属性"关系&计数属性" (即PrimaryRouter)。 如何在调用中添加对象掩码才能看到这些属性?

2 个答案:

答案 0 :(得分:0)

原因是为了从API中的对象获取关系数据,你必须在API调用中声明一个对象掩码,据我所知,它没有在你的代码中声明,它应该是类似的这样:

func getPrivateVlan(env string) (string, error) {
// 1. Create a session
sess := session.New(user, pass)
// 2. Get a service
accountService := services.GetAccountService(sess)

//declare Mask
object_mask := "id;name;primaryRouter"

// 3. Invoke a method including the Object mask:
vlans, err := accountService.Mask(object_mask).GetNetworkVlans()

vlan := vlans[0]
log.Println(*vlan.Name)           //works
log.Println(*vlan.PrimaryRouter)  //
}

请尝试以下代码:

package main

import (
"fmt"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/session"
"encoding/json"
)

func main() {
// SoftLayer API username and key
username := "set-me"
apikey   := "set-me"

// Create a session
sess := session.New(username, apikey)

// Get SoftLayer_Account service
service := services.GetAccountService(sess)

// Object-Mask to get specific Vlan's information
mask := "id;name;primaryRouter"

// Call to getNetworkVlans in order to retrieve vlans according to filter.
result, err := service.Mask(mask).GetNetworkVlans()
if err != nil {
    fmt.Printf("\n Unable to retrieve vlans:\n - %s\n", err)
    return
}

// Following helps to print the result in json format.
jsonFormat, jsonErr := json.MarshalIndent(result,"","     ")
if jsonErr != nil {
    fmt.Println(jsonErr)
    return
}
fmt.Println(string(jsonFormat))
}

有关详细信息,请参阅以下内容:

https://sldn.softlayer.com/article/object-masks#Property_Set

答案 1 :(得分:0)

来源:Unable to get itemCategory info from call GetConfiguration when called from golang

F.Ojeda: 默认端点是REST,但在您的环境中,您使用的是xmlrpc,这可能是由于〜/ .softlayer文件的存在而导致的,因此它被配置为XMLRPC端点。

有关详细信息,请参阅以下文档:https://github.com/softlayer/softlayer-go

此问题适用于XMLRPC enpoint,您可以在go GitHub中报告它。 https://github.com/softlayer/softlayer-go/issues/

尝试使用REST端点编写代码,如下例所示:

endpoint := "https://api.softlayer.com/rest/v3"

// Create a session
sess := session.New(username, apikey, endpoint)