{"id":13670479,"url":"https://github.com/dapr/go-sdk","last_synced_at":"2025-05-14T03:06:02.361Z","repository":{"id":37663934,"uuid":"214236374","full_name":"dapr/go-sdk","owner":"dapr","description":"Dapr SDK for go","archived":false,"fork":false,"pushed_at":"2025-04-14T18:16:06.000Z","size":23290,"stargazers_count":451,"open_issues_count":83,"forks_count":176,"subscribers_count":22,"default_branch":"main","last_synced_at":"2025-04-14T23:15:30.583Z","etag":null,"topics":["binding","component","dapr","events","microservice","pubsub","state"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dapr.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-10-10T16:48:33.000Z","updated_at":"2025-04-08T16:58:30.000Z","dependencies_parsed_at":"2023-11-06T02:40:46.206Z","dependency_job_id":"ec0a7e65-819e-46b8-b135-433d57f1f485","html_url":"https://github.com/dapr/go-sdk","commit_stats":{"total_commits":233,"total_committers":61,"mean_commits":3.819672131147541,"dds":0.7811158798283262,"last_synced_commit":"78a1fe63ea19ae2f50b0a276f46571942e0563b2"},"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dapr%2Fgo-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dapr%2Fgo-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dapr%2Fgo-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dapr%2Fgo-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dapr","download_url":"https://codeload.github.com/dapr/go-sdk/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248975329,"owners_count":21192210,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binding","component","dapr","events","microservice","pubsub","state"],"created_at":"2024-08-02T09:00:43.068Z","updated_at":"2025-04-14T23:15:36.835Z","avatar_url":"https://github.com/dapr.png","language":"Go","funding_links":[],"categories":["Uncategorized","Go"],"sub_categories":["Uncategorized"],"readme":"# Dapr SDK for Go\n\nClient library to help you build Dapr application in Go. This client supports all public [Dapr APIs](https://docs.dapr.io/reference/api/) while focusing on idiomatic Go experience and developer productivity. \n\n[![Test](https://github.com/dapr/go-sdk/workflows/Test/badge.svg)](https://github.com/dapr/go-sdk/actions?query=workflow%3ATest) [![Release](https://github.com/dapr/go-sdk/workflows/Release/badge.svg)](https://github.com/dapr/go-sdk/actions?query=workflow%3ARelease) [![Go Report Card](https://goreportcard.com/badge/github.com/dapr/go-sdk)](https://goreportcard.com/report/github.com/dapr/go-sdk) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/dapr/go-sdk) [![codecov](https://codecov.io/gh/dapr/go-sdk/branch/main/graph/badge.svg)](https://codecov.io/gh/dapr/go-sdk) [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fdapr%2Fgo-sdk.svg?type=shield)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fdapr%2Fgo-sdk?ref=badge_shield)\n\n## Usage\n\u003e Assuming you already have [installed](https://golang.org/doc/install) Go\n\nDapr 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 referred to as \"callback\").\n\n### Installing Dapr Go SDK\n\nWith a correctly configured Go toolchain:\n\n```go\ngo get \"github.com/dapr/go-sdk/client\"\n```\n\n### Creating client \n\nImport Dapr Go `client` package:\n\n```go\nimport \"github.com/dapr/go-sdk/client\"\n```\n\n#### Quick start\n\n```go\npackage main\n\nimport (\n    dapr \"github.com/dapr/go-sdk/client\"\n)\n\nfunc main() {\n    client, err := dapr.NewClient()\n    if err != nil {\n        panic(err)\n    }\n    defer client.Close()\n    // TODO: use the client here, see below for examples \n}\n```\n\n`NewClient` function has a default timeout for 5s, but you can customize this timeout by setting the environment variable `DAPR_CLIENT_TIMEOUT_SECONDS`.  \nFor example: \n```go\npackage main\n\nimport (\n\t\"os\"\n\t\n\tdapr \"github.com/dapr/go-sdk/client\"\n)\n\nfunc main() {\n    os.Setenv(\"DAPR_CLIENT_TIMEOUT_SECONDS\", \"3\")\n    client, err := dapr.NewClient()\n    if err != nil {\n        panic(err)\n    }\n    defer client.Close()\n}\n```\n  \nAssuming you have [Dapr CLI](https://docs.dapr.io/getting-started/install-dapr-cli/) installed, you can then launch your app locally like this:\n\n```shell\ndapr run --app-id example-service \\\n         --app-protocol grpc \\\n         --app-port 50001 \\\n         go run main.go\n```\n\nSee the [example folder](./examples) for more working Dapr client examples.\n\n#### Usage\n\nThe Go client supports all the building blocks exposed by Dapr API. Let's review these one by one: \n\n\n##### State \n\nFor simple use-cases, Dapr client provides easy to use `Save`, `Get`, and `Delete` methods: \n\n```go\nctx := context.Background()\ndata := []byte(\"hello\")\nstore := \"my-store\" // defined in the component YAML \n\n// save state with the key key1, default options: strong, last-write\nif err := client.SaveState(ctx, store, \"key1\", data, nil); err != nil {\n    panic(err)\n}\n\n// get state for key key1\nitem, err := client.GetState(ctx, store, \"key1\", nil)\nif err != nil {\n    panic(err)\n}\nfmt.Printf(\"data [key:%s etag:%s]: %s\", item.Key, item.Etag, string(item.Value))\n\n// delete state for key key1\nif err := client.DeleteState(ctx, store, \"key1\", nil); err != nil {\n    panic(err)\n}\n```\n\nFor more granular control, the Dapr Go client exposes `SetStateItem` type, which can be used to gain more control over the state operations and allow for multiple items to be saved at once:\n\n```go     \nitem1 := \u0026dapr.SetStateItem{\n    Key:  \"key1\",\n    Etag: \u0026ETag{\n        Value: \"1\",\n    },\n    Metadata: map[string]string{\n        \"created-on\": time.Now().UTC().String(),\n    },\n    Value: []byte(\"hello\"),\n    Options: \u0026dapr.StateOptions{\n        Concurrency: dapr.StateConcurrencyLastWrite,\n        Consistency: dapr.StateConsistencyStrong,\n    },\n}\n\nitem2 := \u0026dapr.SetStateItem{\n    Key:  \"key2\",\n    Metadata: map[string]string{\n        \"created-on\": time.Now().UTC().String(),\n    },\n    Value: []byte(\"hello again\"),\n}\n\nitem3 := \u0026dapr.SetStateItem{\n    Key:  \"key3\",\n    Etag: \u0026dapr.ETag{\n\tValue: \"1\",\n    },\n    Value: []byte(\"hello again\"),\n}\n\nif err := client.SaveBulkState(ctx, store, item1, item2, item3); err != nil {\n    panic(err)\n}\n```\n\nSimilarly, `GetBulkState` method provides a way to retrieve multiple state items in a single operation:\n\n```go\nkeys := []string{\"key1\", \"key2\", \"key3\"}\nitems, err := client.GetBulkState(ctx, store, keys, nil, 100)\n```\n\nAnd the `ExecuteStateTransaction` method to execute multiple `upsert` or `delete` operations transactionally.\n\n```go\nops := make([]*dapr.StateOperation, 0)\n\nop1 := \u0026dapr.StateOperation{\n    Type: dapr.StateOperationTypeUpsert,\n    Item: \u0026dapr.SetStateItem{\n        Key:   \"key1\",\n        Value: []byte(data),\n    },\n}\nop2 := \u0026dapr.StateOperation{\n    Type: dapr.StateOperationTypeDelete,\n    Item: \u0026dapr.SetStateItem{\n        Key:   \"key2\",\n    },\n}\nops = append(ops, op1, op2)\nmeta := map[string]string{}\nerr := testClient.ExecuteStateTransaction(ctx, store, meta, ops)\n```\n\n##### PubSub \n\nTo publish data onto a topic, the Dapr client provides a simple method:\n\n```go\ndata := []byte(`{ \"id\": \"a123\", \"value\": \"abcdefg\", \"valid\": true }`)\nif err := client.PublishEvent(ctx, \"component-name\", \"topic-name\", data); err != nil {\n    panic(err)\n}\n```\n\n##### Service Invocation \n\nTo invoke a specific method on another service running with Dapr sidecar, the Dapr client provides two options. To invoke a service without any data:\n\n```go \nresp, err := client.InvokeMethod(ctx, \"app-id\", \"method-name\", \"post\")\n``` \n\nAnd to invoke a service with data: \n\n```go \ncontent := \u0026dapr.DataContent{\n    ContentType: \"application/json\",\n    Data:        []byte(`{ \"id\": \"a123\", \"value\": \"demo\", \"valid\": true }`),\n}\n\nresp, err = client.InvokeMethodWithContent(ctx, \"app-id\", \"method-name\", \"post\", content)\n```\n\n##### Bindings\n\nSimilarly to Service, Dapr client provides two methods to invoke an operation on a [Dapr-defined binding](https://docs.dapr.io/developing-applications/building-blocks/bindings/). Dapr supports input, output, and bidirectional bindings.\n\nFor simple, output only binding:\n\n```go\nin := \u0026dapr.InvokeBindingRequest{ Name: \"binding-name\", Operation: \"operation-name\" }\nerr = client.InvokeOutputBinding(ctx, in)\n```\n\nTo invoke method with content and metadata:\n\n```go\nin := \u0026dapr.InvokeBindingRequest{\n    Name:      \"binding-name\",\n    Operation: \"operation-name\",\n    Data: []byte(\"hello\"),\n    Metadata: map[string]string{\"k1\": \"v1\", \"k2\": \"v2\"},\n}\n\nout, err := client.InvokeBinding(ctx, in)\n```\n\n##### Secrets\n\nThe Dapr client also provides access to the runtime secrets that can be backed by any number of secret stores (e.g. Kubernetes Secrets, HashiCorp Vault, or Azure KeyVault):\n\n```go\nopt := map[string]string{\n    \"version\": \"2\",\n}\n\nsecret, err := client.GetSecret(ctx, \"store-name\", \"secret-name\", opt)\n```\n\n##### Distributed Lock \n\nThe Dapr client provides methods to grab a distributed lock and unlock it.\n\nGrab a lock:\n\n```go\nctx := context.Background()\nstore := \"my-store\" // defined in the component YAML \n\nr, err := testClient.TryLockAlpha1(ctx, testLockStore, \u0026LockRequest{\n    LockOwner:         \"owner1\",\n\tResourceID:      \"resource1\",\n    ExpiryInSeconds: 5,\n})\n```\n\nUnlock a lock:\n\n```go\nr, err := testClient.UnlockAlpha1(ctx, testLockStore, \u0026UnlockRequest{\n\tLockOwner:    \"owner1\",\n\tResourceID: \"resource1\",\n})\n```\n\n##### Authentication\n\nBy 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:\n\n###### Environment Variable\n\nIf the `DAPR_API_TOKEN` environment variable is defined, Dapr will automatically use it to augment its Dapr API invocations to ensure authentication. \n\n###### Explicit Method\n\nIn 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. \n\n```go\nfunc main() {\n    client, err := dapr.NewClient()\n    if err != nil {\n        panic(err)\n    }\n    defer client.Close()\n    client.WithAuthToken(\"your-Dapr-API-token-here\")\n}\n```\n\n##### Error handling\n\nDapr errors are based on [gRPC's richer error model](https://cloud.google.com/apis/design/errors#error_model). \nThe following code shows how to parse and handle the error details:\n\n```go\nif err != nil {\n    st := status.Convert(err)\n\n    fmt.Printf(\"Code: %s\\n\", st.Code().String())\n    fmt.Printf(\"Message: %s\\n\", st.Message())\n\n    for _, detail := range st.Details() {\n        switch t := detail.(type) {\n        case *errdetails.ErrorInfo:\n            // Handle ErrorInfo details\n            fmt.Printf(\"ErrorInfo:\\n- Domain: %s\\n- Reason: %s\\n- Metadata: %v\\n\", t.GetDomain(), t.GetReason(), t.GetMetadata())\n        case *errdetails.BadRequest:\n            // Handle BadRequest details\n            fmt.Println(\"BadRequest:\")\n            for _, violation := range t.GetFieldViolations() {\n                fmt.Printf(\"- Key: %s\\n\", violation.GetField())\n                fmt.Printf(\"- The %q field was wrong: %s\\n\", violation.GetField(), violation.GetDescription())\n            }\n        case *errdetails.ResourceInfo:\n            // Handle ResourceInfo details\n            fmt.Printf(\"ResourceInfo:\\n- Resource type: %s\\n- Resource name: %s\\n- Owner: %s\\n- Description: %s\\n\",\n                t.GetResourceType(), t.GetResourceName(), t.GetOwner(), t.GetDescription())\n        case *errdetails.Help:\n            // Handle ResourceInfo details\n            fmt.Println(\"HelpInfo:\")\n            for _, link := range t.GetLinks() {\n                fmt.Printf(\"- Url: %s\\n\", link.Url)\n                fmt.Printf(\"- Description: %s\\n\", link.Description)\n            }\n        \n        default:\n            // Add cases for other types of details you expect\n            fmt.Printf(\"Unhandled error detail type: %v\\n\", t)\n        }\n    }\n}\n```\n\n### Service (callback)\n\nIn 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](./service/Readme.md).\n\n## Contributing to Dapr Go client\n\nSee the [Contribution Guide](./CONTRIBUTING.md) to get started with building and developing.\n\n## Code of Conduct\n\nPlease refer to our [Dapr Community Code of Conduct](https://github.com/dapr/community/blob/master/CODE-OF-CONDUCT.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdapr%2Fgo-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdapr%2Fgo-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdapr%2Fgo-sdk/lists"}