Getting started with the Dapr Service (Callback) SDK for Go

    Start by importing Dapr Go service/grpc package:

    To create a gRPC Dapr service, first, create a Dapr callback instance with a specific address:

    1. if err != nil {
    2. log.Fatalf("failed to start the server: %v", err)
    3. }
    1. list, err := net.Listen("tcp", "localhost:0")
    2. if err != nil {
    3. }
    4. s := daprd.NewServiceWithListener(list)

    Once you create a service instance, you can “attach” to that service any number of event, binding, and service invocation logic handlers as shown below. Onces the logic is defined, you are ready to start the service:

    To handle events from specific topic you need to add at least one topic event handler before starting the service:

    1. sub := &common.Subscription{
    2. PubsubName: "messages",
    3. }
    4. if err := s.AddTopicEventHandler(sub, eventHandler); err != nil {
    5. log.Fatalf("error adding topic subscription: %v", err)
    6. }
    1. func eventHandler(ctx context.Context, e *common.TopicEvent) (retry bool, err error) {
    2. log.Printf("event - PubsubName:%s, Topic:%s, ID:%s, Data: %v", e.PubsubName, e.Topic, e.ID, e.Data)
    3. // do something with the event
    4. return true, nil

    To handle service invocations you will need to add at least one service invocation handler before starting the service:

    The handler method itself can be any method with the expected signature:

    1. func echoHandler(ctx context.Context, in *common.InvocationEvent) (out *common.Content, err error) {
    2. // do something with the invocation here
    3. out = &common.Content{
    4. Data: in.Data,
    5. ContentType: in.ContentType,
    6. DataTypeURL: in.DataTypeURL,
    7. }
    8. return
    9. }
    1. if err := s.AddBindingInvocationHandler("run", runHandler); err != nil {
    2. log.Fatalf("error adding binding handler: %v", err)

    The handler method itself can be any method with the expected signature: