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:
if err != nil {
log.Fatalf("failed to start the server: %v", err)
}
Or with address and an existing net.Listener in case you want to combine existing server listener:
list, err := net.Listen("tcp", "localhost:0")
if err != nil {
log.Fatalf("gRPC listener creation failed: %s", err)
}
To handle events from specific topic you need to add at least one topic event handler before starting the service:
sub := &common.Subscription{
PubsubName: "messages",
Topic: "topic1",
}
log.Fatalf("error adding topic subscription: %v", err)
}
The handler method itself can be any method with the expected signature:
func eventHandler(ctx context.Context, e *common.TopicEvent) (retry bool, err error) {
log.Printf("event - PubsubName:%s, Topic:%s, ID:%s, Data: %v", e.PubsubName, e.Topic, e.ID, e.Data)
// do something with the event
return true, nil
}
Optionally, you can use routing rules to send messages to different handlers based on the contents of the CloudEvent.
if err := s.AddServiceInvocationHandler("echo", echoHandler); err != nil {
log.Fatalf("error adding invocation handler: %v", err)
}
The handler method itself can be any method with the expected signature:
log.Printf("echo - ContentType:%s, Verb:%s, QueryString:%s, %+v", in.ContentType, in.Verb, in.QueryString, string(in.Data))
out = &common.Content{
Data: in.Data,
ContentType: in.ContentType,
DataTypeURL: in.DataTypeURL,
}
return
}
To handle binding invocations you will need to add at least one binding invocation handler before starting the service:
The handler method itself can be any method with the expected signature:
func runHandler(ctx context.Context, in *common.BindingEvent) (out []byte, err error) {
log.Printf("binding - Data:%v, Meta:%v", in.Data, in.Metadata)
// do something with the invocation here
return nil, nil
}