Working with Vault client on golang

Viewed 7322

I am kind of new comer on golang and Vault. I am trying to store some value/key pairs in secret and then read it. But for me is not so clear how client creation works (in fact should I call it for each operation or I can create one). For example code bellow:

client, err := api.NewClient(conf)
client.SetToken(token)

c := client.Logical()

sec, err := c.Write("/secret/test/" + name,
    map[string]interface{}{ 
        "name": name,
        "username": username,
        "password": password,
    })

It works perfectly. But it looks strange to me to call NewClient each time when I need to write or read something. So I try to create init function for it. Something like this:

var VClient *api.Client // global variable

func InitVault(token string) int{

    conf := &api.Config{
        Address: "http://127.0.0.1:8200",
    }

    VClient, err := api.NewClient(conf)
    if  err != nil {
           log.Println(err)
           return 0
    }

    VClient.SetToken(token)    
    return 1
}

And, it makes an initialization, but when I try to make initialization:

main (){

r := InitVault("token string")

c := VClient.Logical()

    sec, err := c.Write("/secret/test/" + name,
        map[string]interface{}{ 
            "name": name,
            "username": username,
            "password": password,
        })
}

I got a nil pointer exception. There is not so many examples which can really help in this case. Am I wrong and for each and every operation with Vault I need to call NewClient? As I mentioned before it look strange to me, that is why I decided to post my question here, will be glad to get any answers.

Best regards Artur

1 Answers

So as stated by @Volker, you are not updating your already created global variable. So instead you should have something like this. Note that the client is created as another variable which is then passed to the global one.

var VClient *api.Client // global variable

func InitVault(token string) error {
    conf := &api.Config{
        Address: "http://127.0.0.1:8200",
    }

    client, err := api.NewClient(conf)
    if err != nil {
        return err
    }
    VClient = client

    VClient.SetToken(token)
    return nil
}


func main() {
    err := InitVault("root token")
    if err != nil {
        log.Println(err)
    }
    c := VClient.Logical()

    secret, err = c.Write("kv/hi",
    map[string]interface{}{
        "name":     name,
        "username": username,
        "password": password,
    })
    if err != nil {
        log.Println(err)
    }
    log.Println(secret)
}
Related