natsio/utils.go

61 lines
1.5 KiB
Go

package natsio
import (
"encoding/json"
"fmt"
"github.com/nats-io/nats.go"
"strings"
"github.com/thoas/go-funk"
)
// mergeAndUniqueArrayStrings ...
func mergeAndUniqueArrayStrings(arr1, arr2 []string) []string {
var result = make([]string, 0)
result = append(result, arr1...)
result = append(result, arr2...)
result = funk.UniqString(result)
return result
}
func combineStreamAndSubjectName(stream, subject string) string {
return fmt.Sprintf("%s.%s", stream, subject)
}
// GenerateJetStreamSubject ...
func GenerateJetStreamSubject(stream, server, subject string) string {
return fmt.Sprintf("%s.jetstream.%s.%s", stream, server, subject)
}
// GenerateReqrepSubject ...
func GenerateReqrepSubject(stream, server, subject string) string {
return fmt.Sprintf("%s.reqrep.%s.%s", stream, server, subject)
}
func GenerateQueueNameFromSubject(subject string) string {
return strings.ReplaceAll(subject, ".", "_")
}
// InterfaceToBytes ...
func InterfaceToBytes(data interface{}) []byte {
b, err := json.Marshal(data)
if err != nil {
fmt.Printf("[natsio.InterfaceToBytes] error: %v with data: %v\n", err, data)
}
return b
}
func BytesToInterface(b []byte, dest interface{}) error {
err := json.Unmarshal(b, &dest)
if err != nil {
fmt.Printf("[natsio.BytesToInterface] error: %v with data: %s\n", err, string(b))
}
return err
}
func MsgRespond(msg *nats.Msg, data interface{}) {
if err := msg.Respond(InterfaceToBytes(data)); err != nil {
fmt.Printf("[natsio.MsgRespond] error when response msg %s", msg.Reply)
}
}