49 lines
853 B
Go
49 lines
853 B
Go
|
package xmlutils
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/base64"
|
||
|
"encoding/xml"
|
||
|
"io"
|
||
|
)
|
||
|
|
||
|
type nopCloseWriter struct {
|
||
|
io.Writer
|
||
|
}
|
||
|
|
||
|
func (b nopCloseWriter) Close() error {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
const (
|
||
|
nonXML = "nonXML"
|
||
|
typeXML = "application/xml"
|
||
|
)
|
||
|
|
||
|
func DetectXML(data []byte) string {
|
||
|
token, err := xml.NewDecoder(bytes.NewReader(data)).RawToken()
|
||
|
if err != nil {
|
||
|
return nonXML
|
||
|
}
|
||
|
|
||
|
switch token.(type) {
|
||
|
case xml.StartElement, xml.ProcInst:
|
||
|
return typeXML
|
||
|
}
|
||
|
return nonXML
|
||
|
}
|
||
|
|
||
|
func ChooseWriter(dataType string, bodyWriter io.Writer) io.WriteCloser {
|
||
|
if dataType == typeXML {
|
||
|
return nopCloseWriter{bodyWriter}
|
||
|
}
|
||
|
return base64.NewEncoder(base64.StdEncoding, bodyWriter)
|
||
|
}
|
||
|
|
||
|
func ChooseReader(dataType string, bodyReader io.Reader) io.Reader {
|
||
|
if dataType == typeXML {
|
||
|
return bodyReader
|
||
|
}
|
||
|
return base64.NewDecoder(base64.StdEncoding, bodyReader)
|
||
|
}
|