Files
nbi_alarm/core/parse/parse.go
2023-08-24 10:56:16 +08:00

119 lines
2.5 KiB
Go

package parse
import (
"errors"
"fmt"
"omc/core/model"
"strings"
"github.com/aceld/zinx/ziface"
)
// 网元类型#网元标记
type NeBind struct {
NeType string
NeId string
}
// 转换解析服务端绑定的网元
func ConvertBindFlag(bindFlag string) (NeBind, error) {
var neBind NeBind
nb := strings.Split(bindFlag, "#")
if len(nb) != 2 {
return neBind, errors.New("ne bind flag invalid")
}
neBind.NeType = nb[0]
neBind.NeId = nb[1]
return neBind, nil
}
// RequestBodyDecode 请求消息解析
// checker 检查参数必传
func RequestBodyDecode(request ziface.IRequest, checker []string) (model.Body, error) {
// 消息处理
body := model.Body{}
err := Decode(request.GetData(), &body)
if err != nil {
return body, errors.New("inlaid message body")
}
// 检查key
if len(checker) > 0 {
for _, v := range checker {
if _, ok := body.Data[v]; !ok {
return body, errors.New("missing parameter of message body : " + v)
}
}
}
// 当前连接实例ID
uID, err := request.GetConnection().GetProperty("UID")
if err != nil {
request.GetConnection().Stop()
return body, errors.New("server internal error")
}
body.UID = uID.(string)
return body, nil
}
// Decode 数据解析
// reqLoginAlarm;user=yiy;key=qw#$@;type=msg
func Decode(data []byte, body *model.Body) error {
body.RawData = data
multi := strings.Split(string(data), ";")
if len(multi) < 1 {
return errors.New("invalid msg body")
}
// 获取函数名
if multi[0] != "" {
name := multi[0]
idx := strings.LastIndex(name, "\x14")
if idx == -1 {
idx = strings.LastIndex(name, "\x00")
}
if idx == -1 {
idx = strings.LastIndex(name, "\xe2")
}
if idx > 0 {
name = name[idx+1:]
name = strings.Replace(name, "\"", "", 1)
name = strings.Replace(name, "'", "", 1)
name = strings.Replace(name, "#", "", 1)
}
body.Name = name
}
// 解析data KEY
body.Data = make(map[string]string)
for i := 1; i < len(multi); i++ {
str := multi[i]
idx := strings.Index(str, "=")
if idx > 0 {
key := str[:idx]
value := str[idx+1:]
body.Data[key] = value
}
}
return nil
}
// Pack 数据压缩
func Pack(name string, data map[string]string) []byte {
var multi []string
multi = append(multi, name)
// 固定值顺序
keys := []string{"seqNo", "result", "reqId", "resDesc"}
for _, key := range keys {
if v, ok := data[key]; ok {
multi = append(multi, fmt.Sprintf("%s=%s", key, v))
}
}
raw := strings.Join(multi, ";")
return []byte(raw)
}