接口和编码/xml解组
我有一个soap服务,我正在反对它。soap API的一部分用于返回查询结果,我希望提供用于解码信封的基本结构,同时允许开发人员填写编码/xml将解码到的接口接口和编码/xml解组,xml,go,Xml,Go,我有一个soap服务,我正在反对它。soap API的一部分用于返回查询结果,我希望提供用于解码信封的基本结构,同时允许开发人员填写编码/xml将解码到的接口 type QueryEnvelope struct { XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` Body *QueryBody `xml:"http://schemas.xmlsoap.org/soap
type QueryEnvelope struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
Body *QueryBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}
type QueryBody struct {
QueryResult *QueryResult `xml:"queryResponse>result"`
}
type QueryResult struct {
Done bool `xml:"done"`
Size int `xml:"size"`
Records Record `xml:"records"`
}
type Record interface {
UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
}
是否可以注入这样的接口来取消marshall,或者我必须在QueryEnvelope{}级别接受该接口
理想情况下,客户端应采取以下行动:
type Record struct {
Id int `xml:"id"`,
Name stirng `xml:"name"`
}
func (r *Record) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
// unmasrshal here, or best case I dont even need to implment UnmarsahlXML()!
}
res, err := Query("select id from table", Record{})
这意味着他们不必复制QueryEnvelope结构(作为使用我正在创建的包的开发人员)常见的解决方案是要求客户端传递指向其结构实例的指针,如下所示:
// The custom struct of your client
type ClientStruct struct {
Id int `xml:"id"`
Name string `xml:"name"`
}
// This would be your API
func Query(foo string, v interface{}) {
fakeXmlResult := "<test><id>012345</id><name>MyName</name></test>"
xml.Unmarshal([]byte(fakeXmlResult), v)
}
func main() {
r := ClientStruct{}
Query("SQL QUERY", &r) // Note the &
fmt.Println(r)
}
//客户端的自定义结构
类型ClientStruct struct{
Id int`xml:“Id”`
名称字符串`xml:“名称”`
}
//这将是您的API
func查询(foo字符串,v接口{}){
fakeXmlResult:=“012345MyName”
Unmarshal([]字节(fakeXmlResult),v)
}
func main(){
r:=ClientStruct{}
Query(“SQL查询”、&r)//注意&
fmt.Println(右)
}
我是否正确理解了您的问题?因此,您确实可以在中途插入接口,但我未能为解码器分配内存: 包装:
type QueryEnvelope struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
Body *QueryBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}
type QueryBody struct {
QueryResult *QueryResult `xml:"queryResponse>result"`
}
type QueryResult struct {
Done bool `xml:"done"`
Size int `xml:"size"`
Records interface{} `xml:"records"`
}
func (r *Resource) Query(sql string, r interface{}) error {
t := &QueryEnvelope{Body: &QueryBody{QueryResult: &QueryResult{Records: r}}}
//do query and unmarshal into t
return err
}
客户/主要客户:
type Record struct {
Id string `xml:"id"`
Name string `xml:"name"`
}
r := new([]*Record) // must allocate memory using new
err = ent.Query("select id, name from account limit 3", r)
注入接口是什么意思?你能写一个客户端应该能做什么的例子吗?除了最初的问题之外,我已经知道我可以接受一个指针来解码xml。我希望客户端只提供结构上的一部分(QueryResult结构中的记录)。QueryEnvelope、QueryBody和QueryResult总是会被使用,让客户端重新定义它们是多余的