Getting started with the Dapr HTTP Service SDK for Go

How to get up and running with the Dapr HTTP Service SDK for Go

Prerequisite

Start by importing Dapr Go service/http package:

  1. daprd "github.com/dapr/go-sdk/service/http"

Creating and Starting Service

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

  1. s := daprd.NewService(":8080")

Or with address and an existing http.ServeMux in case you want to combine existing server implementations:

  1. mux := http.NewServeMux()
  2. mux.HandleFunc("/", myOtherHandler)
  3. 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:

  1. if err := s.Start(); err != nil && err != http.ErrServerClosed {
  2. log.Fatalf("error: %v", err)
  3. }

Event Handling

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. Topic: "topic1",
  4. Route: "/events",
  5. }
  6. err := s.AddTopicEventHandler(sub, eventHandler)
  7. if err != nil {
  8. log.Fatalf("error adding topic subscription: %v", err)
  9. }

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

  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
  5. }

Service Invocation Handler

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

  1. if err := s.AddServiceInvocationHandler("/echo", echoHandler); err != nil {
  2. log.Fatalf("error adding invocation handler: %v", err)
  3. }

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. log.Printf("echo - ContentType:%s, Verb:%s, QueryString:%s, %+v", in.ContentType, in.Verb, in.QueryString, string(in.Data))
  3. // do something with the invocation here
  4. out = &common.Content{
  5. Data: in.Data,
  6. ContentType: in.ContentType,
  7. DataTypeURL: in.DataTypeURL,
  8. }
  9. return
  10. }

Binding Invocation Handler

  1. if err := s.AddBindingInvocationHandler("/run", runHandler); err != nil {
  2. log.Fatalf("error adding binding handler: %v", err)
  3. }

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

  1. func runHandler(ctx context.Context, in *common.BindingEvent) (out []byte, err error) {
  2. log.Printf("binding - Data:%v, Meta:%v", in.Data, in.Metadata)
  3. // do something with the invocation here
  4. return nil, nil
  5. }