All Projects → dapr → Go Sdk

dapr / Go Sdk

Licence: mit
Dapr SDK for go

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Go Sdk

Samples
Community driven repository for Dapr samples
Stars: ✭ 104 (-30.2%)
Mutual labels:  events, pubsub, state, binding
Nanocomponent
🚃 - create performant HTML components
Stars: ✭ 355 (+138.26%)
Mutual labels:  events, component
Pg Listen
📡 PostgreSQL LISTEN & NOTIFY for node.js that finally works.
Stars: ✭ 348 (+133.56%)
Mutual labels:  events, pubsub
Remit
RabbitMQ-backed microservices supporting RPC, pubsub, automatic service discovery and scaling with no code changes.
Stars: ✭ 24 (-83.89%)
Mutual labels:  microservice, events
watermill-http
HTTP Pub/Sub for the Watermill project.
Stars: ✭ 16 (-89.26%)
Mutual labels:  events, pubsub
Circuits
circuits is a Lightweight Event driven and Asynchronous Application Framework for the Python Programming Language with a strong Component Architecture.
Stars: ✭ 256 (+71.81%)
Mutual labels:  events, component
Hemera
🔬 Writing reliable & fault-tolerant microservices in Node.js https://hemerajs.github.io/hemera/
Stars: ✭ 773 (+418.79%)
Mutual labels:  microservice, pubsub
dry-events
Pub/sub system
Stars: ✭ 102 (-31.54%)
Mutual labels:  events, pubsub
Event Dispatcher
The EventDispatcher component provides tools that allow your application components to communicate with each other by dispatching events and listening to them.
Stars: ✭ 7,946 (+5232.89%)
Mutual labels:  events, component
Rabbitevents
Nuwber's events provide a simple observer implementation, allowing you to listen for various events that occur in your current and another application. For example, if you need to react to some event published from another API.
Stars: ✭ 84 (-43.62%)
Mutual labels:  microservice, events
Lile
Easily generate gRPC services in Go ⚡️
Stars: ✭ 1,271 (+753.02%)
Mutual labels:  microservice, pubsub
observable ish
Observable state and events for browser and Flutter.
Stars: ✭ 26 (-82.55%)
Mutual labels:  events, binding
watermill-amqp
AMQP Pub/Sub for the Watermill project.
Stars: ✭ 27 (-81.88%)
Mutual labels:  events, pubsub
Wisper
A micro library providing Ruby objects with Publish-Subscribe capabilities
Stars: ✭ 3,014 (+1922.82%)
Mutual labels:  events, pubsub
pg-pubsub
Reliable PostgreSQL LISTEN/NOTIFY with inter-process lock support
Stars: ✭ 50 (-66.44%)
Mutual labels:  events, pubsub
Twitchlib
C# Twitch Chat, Whisper, API and PubSub Library. Allows for chatting, whispering, stream event subscription and channel/account modification. Supports .NET Core 2.0
Stars: ✭ 519 (+248.32%)
Mutual labels:  events, pubsub
angular-PubSub
Angular 1.x implementation of the Publish–Subscribe pattern.
Stars: ✭ 32 (-78.52%)
Mutual labels:  events, pubsub
dead-simple
💀💡 Dead simple PubSub and EventEmitter in JavaScript
Stars: ✭ 21 (-85.91%)
Mutual labels:  events, pubsub
Eventing
Open source specification and implementation of Knative event binding and delivery
Stars: ✭ 980 (+557.72%)
Mutual labels:  events, binding
Query State
Application state in query string
Stars: ✭ 88 (-40.94%)
Mutual labels:  state, binding

Dapr SDK for Go

Client library to help you build Dapr application in Go. This client supports all public Dapr APIs while focusing on idiomatic Go experience and developer productivity.

Test Release Go Report Card GitHub go.mod Go version codecov

Usage

Assuming you already have installed Go

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

Creating 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, 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

See the example folder for more working Dapr client examples.

Usage

The Go client supports all the building blocks exposed by Dapr API. Let's review these one by one:

State

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

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

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",
    Metadata: map[string]string{
        "created-on": time.Now().UTC().String(),
    },
    Value: []byte("hello again"),
}

item3 := &dapr.SetStateItem{
    Key:  "key3",
    Etag: "1",
    Value: []byte("hello again"),
}

if err := client.SaveStateItems(ctx, store, item1, item2, item3); err != nil {
    panic(err)
}

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

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

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

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.InvokeMethod(ctx, "app-id", "method-name") 

And to invoke a service with data:

content := &dapr.DataContent{
    ContentType: "application/json",
    Data:        []byte(`{ "id": "a123", "value": "demo", "valid": true }`),
}

resp, err := client.InvokeMethodWithContent(ctx, "app-id", "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 := &dapr.InvokeBindingRequest{ Name: "binding-name", Operation: "operation-name" }
err = client.InvokeOutputBinding(ctx, in)

To invoke method with content and metadata:

in := &dapr.InvokeBindingRequest{
    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)

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.

func main() {
    client, err := dapr.NewClient()
    if err != nil {
        panic(err)
    }
    defer client.Close()
    client.WithAuthToken("your-Dapr-API-token-here")
}

Service (callback)

In addition to the client capabilities that allow you to call into the Dapr API, the Go SDK also provides service package to help you bootstrap Dapr callback services in either gRPC or HTTP. 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.

Code of Conduct

Please refer to our Dapr Community Code of Conduct

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].