Getting started with the Dapr HTTP Service SDK for Go
Start by importing Dapr Go service/http package:
To create an HTTP Dapr service, first, create a Dapr callback instance with a specific address:
mux := http.NewServeMux()
mux.HandleFunc("/", myOtherHandler)
s := daprd.NewServiceWithMux(":8080", mux)
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:
sub := &common.Subscription{
PubsubName: "messages",
Route: "/events",
}
err := s.AddTopicEventHandler(sub, eventHandler)
log.Fatalf("error adding topic subscription: %v", err)
}
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
}
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:
func echoHandler(ctx context.Context, in *common.InvocationEvent) (out *common.Content, err error) {
out = &common.Content{
Data: in.Data,
ContentType: in.ContentType,
DataTypeURL: in.DataTypeURL,
}
return
}
if err := s.AddBindingInvocationHandler("/run", runHandler); err != nil {
log.Fatalf("error adding binding handler: %v", err)