Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PDR-16879][feat]: xml transformer add encodig #1213

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions transforms/mutate/xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ package mutate

import (
"errors"
"io"
"strconv"
"strings"
"sync"

"github.com/clbanning/mxj"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"

"github.com/qiniu/log"
"github.com/qiniu/logkit/transforms"
. "github.com/qiniu/logkit/utils/models"
)
Expand All @@ -19,12 +23,13 @@ var (
)

type Xml struct {
Key string `json:"key"`
New string `json:"new"`
Keep bool `json:"keep"`
Expand bool `json:"expand"`
DiscardKey bool `json:"discard_key"`
NoAttr bool `json:"no_attr"`
Key string `json:"key"`
New string `json:"new"`
Encoding string `json:"encoding"`
stats StatsInfo

keys []string
Expand Down Expand Up @@ -61,6 +66,21 @@ func (g *Xml) Init() error {
numRoutine = 1
}
g.numRoutine = numRoutine

if len(g.Encoding) != 0 {
g.Encoding = strings.ToLower(g.Encoding)
switch g.Encoding {
case "utf8", "utf-8":
break
case "gbk", "gb2312", "gb18030":
mxj.XmlCharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
return transform.NewReader(input, simplifiedchinese.GBK.NewDecoder()), nil
}
default:
log.Warn("unsupported encoding: %s, use utf-8 default", g.Encoding)
}
}

return nil
}

Expand Down Expand Up @@ -155,6 +175,16 @@ func (g *Xml) ConfigOptions() []Option {
return []Option{
transforms.KeyFieldName,
transforms.KeyFieldNew,
{
KeyName: "encoding",
ChooseOnly: true,
ChooseOptions: []interface{}{"UTF-8", "GBK", "GB2312"},
Default: "UTF-8",
DefaultNoUse: false,
Description: "编码方式(encoding)",
Advance: true,
ToolTip: "读取日志的编码方式,默认为UTF-8,即按照UTF-8的编码方式读取文件",
},
transforms.KeyKeepString,
transforms.KeyDiscardkey,
{
Expand Down Expand Up @@ -240,6 +270,7 @@ func (g *Xml) transform(dataPipeline <-chan transforms.TransformInfo, resultChan

m, xmlErr := mxj.NewMapXml([]byte(strVal), g.Keep)
if xmlErr != nil {
log.Warnf("xml parse error: %v", xmlErr)
errNum, err = transforms.SetError(errNum, xmlErr, transforms.General, "")
resultChan <- transforms.TransformResult{
Index: transformInfo.Index,
Expand Down