Client

The Dapr client package allows you to interact with other Dapr applications from a Go application.

Prerequisites

Import the client package

  1. import "github.com/dapr/go-sdk/client"

Building blocks

The Go SDK allows you to interface with all of the Dapr building blocks.

Service Invocation

To invoke a specific method on another service running with Dapr sidecar, the Dapr client Go SDK provides two options:

Invoke a service without data:

  1. resp, err := client.InvokeMethod(ctx, "app-id", "method-name", "post")

Invoke a service with data:

  1. content := &dapr.DataContent{
  2. ContentType: "application/json",
  3. Data: []byte(`{ "id": "a123", "value": "demo", "valid": true }`),
  4. }
  5. resp, err = client.InvokeMethodWithContent(ctx, "app-id", "method-name", "post", content)

For a full guide on service invocation, visit How-To: Invoke a service.

State Management

For simple use-cases, Dapr client provides easy to use Save, Get, Delete methods:

  1. ctx := context.Background()
  2. data := []byte("hello")
  3. store := "my-store" // defined in the component YAML
  4. // save state with the key key1, default options: strong, last-write
  5. if err := client.SaveState(ctx, store, "key1", data, nil); err != nil {
  6. panic(err)
  7. }
  8. // get state for key key1
  9. item, err := client.GetState(ctx, store, "key1", nil)
  10. if err != nil {
  11. panic(err)
  12. }
  13. fmt.Printf("data [key:%s etag:%s]: %s", item.Key, item.Etag, string(item.Value))
  14. // delete state for key key1
  15. if err := client.DeleteState(ctx, store, "key1", nil); err != nil {
  16. panic(err)
  17. }

For more granular control, the Dapr Go client exposes SetStateItem type, which can be use to gain more control over the state operations and allow for multiple items to be saved at once:

  1. item1 := &dapr.SetStateItem{
  2. Key: "key1",
  3. Etag: &ETag{
  4. Value: "1",
  5. },
  6. Metadata: map[string]string{
  7. "created-on": time.Now().UTC().String(),
  8. },
  9. Value: []byte("hello"),
  10. Options: &dapr.StateOptions{
  11. Concurrency: dapr.StateConcurrencyLastWrite,
  12. Consistency: dapr.StateConsistencyStrong,
  13. },
  14. }
  15. item2 := &dapr.SetStateItem{
  16. Key: "key2",
  17. Metadata: map[string]string{
  18. "created-on": time.Now().UTC().String(),
  19. },
  20. Value: []byte("hello again"),
  21. }
  22. item3 := &dapr.SetStateItem{
  23. Key: "key3",
  24. Etag: &dapr.ETag{
  25. Value: "1",
  26. },
  27. Value: []byte("hello again"),
  28. }
  29. if err := client.SaveBulkState(ctx, store, item1, item2, item3); err != nil {
  30. panic(err)
  31. }

Similarly, GetBulkState method provides a way to retrieve multiple state items in a single operation:

  1. keys := []string{"key1", "key2", "key3"}
  2. items, err := client.GetBulkState(ctx, store, keys, nil,100)

And the ExecuteStateTransaction method to execute multiple upsert or delete operations transactionally.

  1. ops := make([]*dapr.StateOperation, 0)
  2. op1 := &dapr.StateOperation{
  3. Type: dapr.StateOperationTypeUpsert,
  4. Item: &dapr.SetStateItem{
  5. Key: "key1",
  6. Value: []byte(data),
  7. },
  8. }
  9. op2 := &dapr.StateOperation{
  10. Type: dapr.StateOperationTypeDelete,
  11. Item: &dapr.SetStateItem{
  12. Key: "key2",
  13. },
  14. }
  15. ops = append(ops, op1, op2)
  16. meta := map[string]string{}
  17. err := testClient.ExecuteStateTransaction(ctx, store, meta, ops)

For a full guide on state management, visit How-To: Save & get state.

Publish Messages

To publish data onto a topic, the Dapr Go client provides a simple method:

  1. data := []byte(`{ "id": "a123", "value": "abcdefg", "valid": true }`)
  2. if err := client.PublishEvent(ctx, "component-name", "topic-name", data); err != nil {
  3. panic(err)
  4. }

For a full guide on pub/sub, visit How-To: Publish & subscribe.

Output Bindings

The Dapr Go client SDK provides two methods to invoke an operation on a Dapr-defined binding. Dapr supports input, output, and bidirectional bindings.

For simple, output-only binding:

  1. in := &dapr.InvokeBindingRequest{ Name: "binding-name", Operation: "operation-name" }
  2. err = client.InvokeOutputBinding(ctx, in)

To invoke method with content and metadata:

  1. in := &dapr.InvokeBindingRequest{
  2. Name: "binding-name",
  3. Operation: "operation-name",
  4. Data: []byte("hello"),
  5. Metadata: map[string]string{"k1": "v1", "k2": "v2"},
  6. }
  7. out, err := client.InvokeBinding(ctx, in)

For a full guide on output bindings, visit How-To: Use bindings.

Secret Management

The Dapr client also provides access to the runtime secrets that can be backed by any number of secrete stores (e.g. Kubernetes Secrets, HashiCorp Vault, or Azure KeyVault):

  1. opt := map[string]string{
  2. "version": "2",
  3. }
  4. secret, err := client.GetSecret(ctx, "store-name", "secret-name", opt)

Authentication

By default, Dapr relies on the network boundary to limit access to its API. If however the target Dapr API is configured with token-based authentication, users can configure the Go Dapr client with that token in two ways:

Environment Variable

If the DAPR_API_TOKEN environment variable is defined, Dapr will automatically use it to augment its Dapr API invocations to ensure authentication.

Explicit Method

In addition, users can also set the API token explicitly on any Dapr client instance. This approach is helpful in cases when the user code needs to create multiple clients for different Dapr API endpoints.

  1. func main() {
  2. client, err := dapr.NewClient()
  3. if err != nil {
  4. panic(err)
  5. }
  6. defer client.Close()
  7. client.WithAuthToken("your-Dapr-API-token-here")
  8. }

For a full guide on secrets, visit How-To: Retrieve secrets.

Distributed Lock

The Dapr client provides mutually exclusive access to a resource using a lock. With a lock, you can:

  • Provide access to a database row, table, or an entire database
  • Lock reading messages from a queue in a sequential manner
  1. package main
  2. import (
  3. "fmt"
  4. dapr "github.com/dapr/go-sdk/client"
  5. )
  6. func main() {
  7. client, err := dapr.NewClient()
  8. if err != nil {
  9. panic(err)
  10. }
  11. defer client.Close()
  12. resp, err := client.TryLockAlpha1(ctx, "lockstore", &dapr.LockRequest{
  13. LockOwner: "random_id_abc123",
  14. ResourceID: "my_file_name",
  15. ExpiryInSeconds: 60,
  16. })
  17. fmt.Println(resp.Success)
  18. }

For a full guide on distributed lock, visit How-To: Use a lock.

Configuration

With the Dapr client Go SDK, you can consume configuration items that are returned as read-only key/value pairs, and subscribe to configuration item changes.

Config Get

  1. items, err := client.GetConfigurationItem(ctx, "example-config", "mykey")
  2. if err != nil {
  3. panic(err)
  4. }
  5. fmt.Printf("get config = %s\n", (*items).Value)

Config Subscribe

  1. go func() {
  2. if err := client.SubscribeConfigurationItems(ctx, "example-config", []string{"mySubscribeKey1", "mySubscribeKey2", "mySubscribeKey3"}, func(id string, items map[string]*dapr.ConfigurationItem) {
  3. for k, v := range items {
  4. fmt.Printf("get updated config key = %s, value = %s \n", k, v.Value)
  5. }
  6. subscribeID = id
  7. }); err != nil {
  8. panic(err)
  9. }
  10. }()

For a full guide on configuration, visit How-To: Manage configuration from a store.

Cryptography

With the Dapr client Go SDK, you can use the high-level Encrypt and Decrypt cryptography APIs to encrypt and decrypt files while working on a stream of data.

To encrypt:

  1. // Encrypt the data using Dapr
  2. out, err := sdkClient.Encrypt(context.Background(), rf, dapr.EncryptOptions{
  3. // These are the 3 required parameters
  4. ComponentName: "mycryptocomponent",
  5. KeyName: "mykey",
  6. Algorithm: "RSA",
  7. })
  8. if err != nil {
  9. panic(err)
  10. }

To decrypt:

  1. // Decrypt the data using Dapr
  2. out, err := sdkClient.Decrypt(context.Background(), rf, dapr.EncryptOptions{
  3. // Only required option is the component name
  4. ComponentName: "mycryptocomponent",
  5. })

For a full guide on cryptography, visit How-To: Use the cryptography APIs.

Go SDK Examples