client.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package dapr_client
  2. import (
  3. "context"
  4. dapr "github.com/dapr/go-sdk/client"
  5. "time"
  6. )
  7. type Client struct {
  8. client dapr.Client
  9. timeoutSec int64
  10. }
  11. func newClient(timeoutSec int64) (*Client, error) {
  12. client, err := dapr.NewClient()
  13. if err != nil {
  14. return nil, err
  15. }
  16. c := new(Client)
  17. c.client = client
  18. c.timeoutSec = timeoutSec
  19. return c, nil
  20. }
  21. func destroyClient(client *Client) {
  22. if client == nil {
  23. return
  24. }
  25. client.client.Close()
  26. client.client = nil
  27. client = nil
  28. }
  29. func (client *Client) InvokeGetMethod(appID string, methodName string) ([]byte, error) {
  30. return client.invokeMethod(appID, methodName, "get")
  31. }
  32. func (client *Client) InvokePostMethodJson(appID string, methodName string, jsonData []byte) ([]byte, error) {
  33. return client.invokeMethodJson(appID, methodName, "post", jsonData)
  34. }
  35. func (client *Client) InvokePutMethodJson(appID string, methodName string, jsonData []byte) ([]byte, error) {
  36. return client.invokeMethodJson(appID, methodName, "put", jsonData)
  37. }
  38. func (client *Client) InvokeDeleteMethod(appID string, methodName string) ([]byte, error) {
  39. return client.invokeMethod(appID, methodName, "delete")
  40. }
  41. func (client *Client) Publish(pubsubName string, topic string, content []byte) error {
  42. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(client.timeoutSec)*time.Second)
  43. defer cancel()
  44. return client.client.PublishEvent(ctx, pubsubName, topic, content)
  45. }
  46. func (client *Client) invokeMethod(appID string, methodName string, verb string) ([]byte, error) {
  47. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(client.timeoutSec)*time.Second)
  48. defer cancel()
  49. return client.client.InvokeMethod(ctx, appID, methodName, verb)
  50. }
  51. func (client *Client) invokeMethodJson(appID string, methodName string, verb string, jsonData []byte) ([]byte, error) {
  52. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(client.timeoutSec)*time.Second)
  53. defer cancel()
  54. return client.client.InvokeMethodWithContent(ctx, appID, methodName, verb,
  55. &dapr.DataContent{
  56. Data: jsonData,
  57. ContentType: "application/json",
  58. })
  59. }