golang storing map to variable and do asserts

Issue

I am trying to use Avi Go SDK to fetch a gslb configuration.

First initilizing a connection to the controller as below,

aviClient, err := clients.NewAviClient("mycontroller", "USER",
    session.SetPassword("PASSS"),
    session.SetTenant("TENANT"),
    session.SetInsecure)
if err != nil {
    t.Error(err)
}

Then trying to grab a gslb details as below,

//Fetch gslb
var obj interface{}
err = aviClient.AviSession.GetObjectByName("gslbservice", "mygslbname", &obj)
fmt.Printf("%v\n", obj)

and that print the details as below,

map[_last_modified:1650419741251661 controller_health_status_enabled:true created_by:null description:null domain_names:[xxxxxxxxxxxxx] down_response:map[type:GSLB_SERVICE_DOWN_RESPONSE_ALL_RECORDS] enabled:true groups:[map[algorithm:GSLB_ALGORITHM_ROUND_ROBIN members:[map[cluster_uuid:xxxxxxxxxxxxxxxxxxxx enabled:true fqdn:xxxxxxxxxxxxxxxxxxxxxxxxx ip:map[addr:xxxxxxxxxxxxxxx type:V4] location:map[source:GSLB_LOCATION_SRC_INHERIT_FROM_SITE] ratio:1]] name:xxxxxxxxxxxxxxxxxxxxxxx priority:10]] health_monitor_refs:[https://xxxxxxxxxxxxxxxx] health_monitor_scope:GSLB_SERVICE_HEALTH_MONITOR_ALL_MEMBERS name:xxxxxxxxxxxxxxxx num_dns_ip:1 tenant_ref:https://xxxxxxxxxxxxxxxxxxx ttl:30 url:https://xxxxxxxxxxxxxxxxxxxx use_edns_client_subnet:true uuid:xxxxxxxxxxxxxxxxxxx wildcard_match:false]

Now I would like to store that whole map to variable so that I can do asserts and test as below,

var obj1 interface{}    
appDeployment := aviClient.AviSession.GetObjectByName("gslbservice", "mygslbname", &obj1)
if err != nil {
    t.Error(err)
}
assert.Equal(t, appDeployment.domain_names, "mygslbname")

I get below error,

appDeployment.domain_names undefined (type error has no field or method domain_names)

Any assitance?
Or How do print any values from the map, for eg how to print ttl value from above map?

Solution

You have two problems:

  1. GetObjectByName returns error.
    So, your appDeployment is actually an error
  2. You have to access the map by string keys. So, even if appDeployment were a valid map, you would have to access domain_names by string key.

This should solve both problems:

    var obj1 map[string]interface{}

    err = aviClient.AviSession.GetObjectByName("gslbservice", "mygslbname", &obj1)
    if err != nil {
        t.Error(err)
    }
    assert.Equal(t, obj1["domain_names"], "mygslbname")

Answered By – ABDULLOKH MUKHAMMADJONOV

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.