client.go 2.3 KB

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