go-sdk

module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2020 License: MIT

README

Dapr SDK for Go

Client library to accelerate Dapr application development in go. This client supports all public Dapr API and focuses on developer productivity.

Test Release Go Report Card GitHub go.mod Go version

Usage

Assuming you already have installed go

Dapr go client includes two packages: client (for invoking public Dapr API) and service (to create services in go that can be invoked by Dapr, this is sometimes refereed to as "callback").

Client

Import Dapr go client package:

import "github.com/dapr/go-sdk/client"
Quick start
package main

import (
    dapr "github.com/dapr/go-sdk/client"
)

func main() {
    client, err := dapr.NewClient()
    if err != nil {
        panic(err)
    }
    defer client.Close()
    //TODO: use the client here, see below for examples 
}

Assuming you have Dapr CLI installed locally, you can then launch your app locally like this:

dapr run --app-id example-service \
         --app-protocol grpc \
         --app-port 50001 \
         go run main.go

Check the example folder for working Dapr go client examples.

To accelerate your Dapr service development even more, consider the GitHub templates with complete gRPC solutions for two common use-cases:

Usage

The Dapr go client supports following functionality:

State

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

ctx := context.Background()
data := []byte("hello")
store := "my-store" // defined in the component YAML 

// save state with the key key1
if err := client.SaveState(ctx, store, "key1", data); err != nil {
    panic(err)
}

// get state for key key1
item, err := client.GetState(ctx, store, "key1")
if err != nil {
    panic(err)
}
fmt.Printf("data [key:%s etag:%s]: %s", item.Key, item.Etag, string(item.Value))

// delete state for key key1
if err := client.DeleteState(ctx, store, "key1"); err != nil {
    panic(err)
}

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

item1 := &dapr.SetStateItem{
    Key:  "key1",
    Etag: "2",
    Metadata: map[string]string{
        "created-on": time.Now().UTC().String(),
    },
    Value: []byte("hello"),
    Options: &dapr.StateOptions{
        Concurrency: dapr.StateConcurrencyLastWrite,
        Consistency: dapr.StateConsistencyStrong,
    },
}
item2 := &dapr.SetStateItem{
    Key:  "key2",
    Etag: "1",
    Metadata: map[string]string{
        "created-on": time.Now().UTC().String(),
    },
    Value: []byte("hello again"),
    Options: &dapr.StateOptions{
        Concurrency: dapr.StateConcurrencyLastWrite,
        Consistency: dapr.StateConsistencyStrong,
    },
}
if err := client.SaveStateItems(ctx, store, item1, item2); err != nil {
    panic(err)
}

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

keys := []string{"key1", "key2", "key3"}
items, err := GetStateItems(ctx, store, keys, parallelism 100)

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

ops := make([]*dapr.StateOperation, 0)

op1 := &dapr.StateOperation{
    Type: dapr.StateOperationTypeUpsert,
    Item: &dapr.SetStateItem{
        Key:   "key1",
        Value: []byte(data),
    },
}
op2 := &dapr.StateOperation{
    Type: dapr.StateOperationTypeDelete,
    Item: &dapr.SetStateItem{
        Key:   "key2",
    },
}
ops = append(ops, op1, op2)
meta := map[string]string{}
err := testClient.ExecuteStateTransaction(ctx, store, meta, ops)
PubSub

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

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

To invoke a specific method on another service running with Dapr sidecar, the Dapr client provides two options. To invoke a service without any data:

resp, err = client.InvokeService(ctx, "service-name", "method-name") 

And to invoke a service with data:

content := &DataContent{
    ContentType: "application/json",
    Data:        []byte(`{ "id": "a123", "value": "demo", "valid": true }`)
}
resp, err := client.InvokeServiceWithContent(ctx, "service-name", "method-name", content)
Bindings

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

For simple, output only biding:

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

To invoke method with content and metadata:

in := &BindingInvocation{
    Name:      "binding-name",
    Operation: "operation-name",
    Data: []byte("hello"),
    Metadata: map[string]string{"k1": "v1", "k2": "v2"}
}
out, err := client.InvokeBinding(ctx, in)
Secrets

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

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

Service (callback)

In addition to a an easy to use client, Dapr go package also provides implementation for service. Instructions on how to use it are located here

Contributing to Dapr go client

See the Contribution Guide to get started with building and developing.

Directories

Path Synopsis
dapr
example
client command
serving/grpc command
serving/http command
examples module
actor module
configuration module
grpc-service module
hello-world module
pubsub module
service module
socket module
service
tools

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL