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)

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)

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. }

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 biding:

  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)

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. }