service/app/mix/service/esbservice.go

78 lines
1.6 KiB
Go

package service
import (
"bytes"
"io"
"net/http"
"service/api/consts"
"service/library/logger"
"github.com/beevik/etree"
)
var DefaultEsbService *EsbService
type EsbService struct {
RoutingTable map[string]string
}
func NewEsbService() *EsbService {
return new(EsbService)
}
func (s *EsbService) Init() (err error) {
// 初始化路由表
s.RoutingTable = make(map[string]string)
fullPath := consts.EsbRoutingTableConfig
doc := etree.NewDocument()
if err := doc.ReadFromFile(fullPath); err != nil {
logger.Error("read xml failed:%v.", err)
}
root := doc.SelectElement("esb_routing_table")
if root == nil {
logger.Error("read node esb_routing_table failed")
}
msgs := root.FindElements("./msg")
if msgs == nil {
logger.Error("read node msg failed")
}
for _, msg := range msgs {
name := msg.SelectAttrValue("name", "")
url := msg.Text()
s.RoutingTable[name] = url
}
return
}
// 发送消息
func (s *EsbService) SendMsg(msgNo string, msg []byte) (resp []byte, err error) {
// 取路由地址
url := s.RoutingTable[msgNo]
// 组装请求报文
req, err := http.NewRequest("POST", url, bytes.NewBuffer(msg))
if err != nil {
logger.Error("http NewRequest fail, err: %v", err)
return
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := http.DefaultClient
response, err := client.Do(req)
if err != nil {
logger.Error("client Do fail, err: %v", err)
return
}
defer response.Body.Close()
resp, err = io.ReadAll(response.Body)
if err != nil {
logger.Error("response read fail, err: %v", err)
return
}
return
}