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)

Retrieve, filter, and sort key/value data stored in your statestore using QueryState.

  1. // Define the query string
  2. query := `{
  3. "filter": {
  4. "EQ": { "value.Id": "1" }
  5. },
  6. "sort": [
  7. {
  8. "key": "value.Balance",
  9. "order": "DESC"
  10. }
  11. ]
  12. }`
  13. // Use the client to query the state
  14. queryResponse, err := c.QueryState(ctx, "querystore", query)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. fmt.Printf("Got %d\n", len(queryResponse))
  19. for _, account := range queryResponse {
  20. var data Account
  21. err := account.Unmarshal(&data)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. fmt.Printf("Account: %s has %f\n", data.ID, data.Balance)
  26. }

Note: Query state API is currently in alpha

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

To publish multiple messages at once, the PublishEvents method can be used:

  1. events := []string{"event1", "event2", "event3"}
  2. res := client.PublishEvents(ctx, "component-name", "topic-name", events)
  3. if res.Error != nil {
  4. panic(res.Error)
  5. }

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.

Actors

Use the Dapr Go client SDK to write actors.

  1. // MyActor represents an example actor type.
  2. type MyActor struct {
  3. actors.Actor
  4. }
  5. // MyActorMethod is a method that can be invoked on MyActor.
  6. func (a *MyActor) MyActorMethod(ctx context.Context, req *actors.Message) (string, error) {
  7. log.Printf("Received message: %s", req.Data)
  8. return "Hello from MyActor!", nil
  9. }
  10. func main() {
  11. // Create a Dapr client
  12. daprClient, err := client.NewClient()
  13. if err != nil {
  14. log.Fatal("Error creating Dapr client: ", err)
  15. }
  16. // Register the actor type with Dapr
  17. actors.RegisterActor(&MyActor{})
  18. // Create an actor client
  19. actorClient := actors.NewClient(daprClient)
  20. // Create an actor ID
  21. actorID := actors.NewActorID("myactor")
  22. // Get or create the actor
  23. err = actorClient.SaveActorState(context.Background(), "myactorstore", actorID, map[string]interface{}{"data": "initial state"})
  24. if err != nil {
  25. log.Fatal("Error saving actor state: ", err)
  26. }
  27. // Invoke a method on the actor
  28. resp, err := actorClient.InvokeActorMethod(context.Background(), "myactorstore", actorID, "MyActorMethod", &actors.Message{Data: []byte("Hello from client!")})
  29. if err != nil {
  30. log.Fatal("Error invoking actor method: ", err)
  31. }
  32. log.Printf("Response from actor: %s", resp.Data)
  33. // Wait for a few seconds before terminating
  34. time.Sleep(5 * time.Second)
  35. // Delete the actor
  36. err = actorClient.DeleteActor(context.Background(), "myactorstore", actorID)
  37. if err != nil {
  38. log.Fatal("Error deleting actor: ", err)
  39. }
  40. // Close the Dapr client
  41. daprClient.Close()
  42. }

For a full guide on actors, visit the Actors building block documentation.

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