Files
nbi_alarm/core/parse/parse.go
2023-08-25 12:03:19 +08:00

127 lines
2.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
// 允许的拓展字段 "seqNo", "fileName"
// 固定值顺序 "result", "reqId", "resDesc"
keys := []string{"seqNo", "reqId", "result", "fileName", "resDesc"}
for _, key := range keys {
if v, ok := data[key]; ok {
// 长度小于32个字符不允许带分号“;”
if key == "resDesc" && len(v) > 32 {
v = v[0:32]
}
if key == "resDesc" && strings.Contains(v, ";") {
v = strings.ReplaceAll(v, ";", "")
}
multi = append(multi, fmt.Sprintf("%s=%s", key, v))
}
}
raw := strings.Join(multi, ";")
return []byte(raw)
}