12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package pubsub
- import (
- "fmt"
- "git.sxidc.com/service-supports/dapr_api/utils"
- "github.com/go-resty/resty/v2"
- "time"
- )
- const (
- publishUrlFormat = "http://localhost:%d/v1.0/publish/%s/%s"
- )
- type API struct {
- client *resty.Client
- port int
- }
- func NewAPI(port int, timeout time.Duration) *API {
- return &API{
- client: resty.New().SetTimeout(timeout),
- port: port,
- }
- }
- func DestroyAPI(api *API) {
- if api == nil {
- return
- }
- api.port = 0
- api.client = nil
- }
- func (api *API) Publish(pubsubName string, topic string, data string, queryParams map[string]string) error {
- return api.publish(pubsubName, topic, "test/plain", data, queryParams)
- }
- func (api *API) PublishJSON(pubsubName string, topic string, data string, queryParams map[string]string) error {
- return api.publish(pubsubName, topic, "application/json", data, queryParams)
- }
- func (api *API) publish(pubsubName string, topic string, contentType string, data string,
- queryParams map[string]string) error {
- publishUrl := fmt.Sprintf(publishUrlFormat, api.port, pubsubName, topic)
- resp, err := api.client.R().
- SetHeader("Content-Type", contentType).
- SetQueryParams(queryParams).
- SetBody(data).
- Post(publishUrl)
- if err != nil {
- return err
- }
- if resp.IsError() {
- return utils.ResponseStatusError(publishUrl, resp)
- }
- return nil
- }
|