#Initializing Dagger client in a reusable function

1 messages · Page 1 of 1 (latest)

sacred veldt
#

I'm trying to initialize the Dagger client as a reusable function when using the Go SDK.

func InitializeDagger(ctx context.Context) dagger.Client {
client, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stdout))
if err != nil {
panic(err)
}
defer client.Close()

return client

}

// Calling above function
ctx := context.Background()
client := common.InitializeDagger(ctx)

Unfortunately, I run into the error below - has anyone seen this before? I feel like I'm overlooking something simple 😅

panic: Post "http://dagger/query": dial tcp 127.0.0.1:54527: connectex: No connection could be made because the target machine actively refused it.

raw leaf
#

i think it’s because of defer client.Close()

#

Basically your function returns a closed client

#

I think if you remove just that line, everything should work

#

also, you could take it one step further and make your dagger client a global variable, initialized in your package init()

#
package main

var dag *dagger.Client

func init() {
 if c, err := dagger.Connect(context.Background()); err != nil {
  panic(err)
 } else {
  dag = c
 }
}