pubsub.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package pubsub
  2. import (
  3. "fmt"
  4. "github.com/go-resty/resty/v2"
  5. "time"
  6. )
  7. const (
  8. publishUrlFormat = "http://localhost:%d/v1.0/publish/%s/%s"
  9. )
  10. type API struct {
  11. port int
  12. client *resty.Client
  13. }
  14. func NewAPI(port int, timeout time.Duration) *API {
  15. return &API{
  16. client: resty.New().SetTimeout(timeout),
  17. port: port,
  18. }
  19. }
  20. func DestroyAPI(api *API) {
  21. if api == nil {
  22. return
  23. }
  24. api.port = 0
  25. api.client = nil
  26. }
  27. func (api *API) Publish(pubsubName string, topic string, data string, queryParams map[string]string) error {
  28. return api.publish(pubsubName, topic, "test/plain", data, queryParams)
  29. }
  30. func (api *API) PublishJSON(pubsubName string, topic string, data string, queryParams map[string]string) error {
  31. return api.publish(pubsubName, topic, "application/json", data, queryParams)
  32. }
  33. func (api *API) publish(pubsubName string, topic string, contentType string, data string,
  34. queryParams map[string]string) error {
  35. publishUrl := fmt.Sprintf(publishUrlFormat, api.port, pubsubName, topic)
  36. resp, err := api.client.R().
  37. SetHeader("Content-Type", contentType).
  38. SetQueryParams(queryParams).
  39. SetBody(data).
  40. Post(publishUrl)
  41. if err != nil {
  42. return err
  43. }
  44. if resp.IsError() {
  45. return fmt.Errorf("Status %d: %s\n", resp.StatusCode(), resp.Body())
  46. }
  47. return nil
  48. }