package utils import ( "bytes" "encoding/base64" "encoding/xml" "errors" "io" ) const BodyRecognizeLimit int64 = 128 func DetectXML(reader io.Reader) (bool, []byte, error) { checkBuf := bytes.NewBuffer(nil) token, err := xml.NewDecoder(io.TeeReader(io.LimitReader(reader, BodyRecognizeLimit), checkBuf)).RawToken() if err != nil { var xmlErr *xml.SyntaxError if errors.Is(err, io.EOF) || errors.As(err, &xmlErr) { return false, checkBuf.Bytes(), nil } return false, checkBuf.Bytes(), err } switch token.(type) { case xml.StartElement, xml.ProcInst: return true, checkBuf.Bytes(), nil } return false, checkBuf.Bytes(), nil } func ChooseWriter(isXML bool, body *bytes.Buffer) io.Writer { if !isXML { return base64.NewEncoder(base64.StdEncoding, body) } return body } func ChooseReader(isXml bool, bodyReader io.Reader) io.Reader { if !isXml { return base64.NewDecoder(base64.StdEncoding, bodyReader) } return bodyReader }