gpt4 book ai didi

go - 在 Go 中解码 SOAP 响应

转载 作者:IT王子 更新时间:2023-10-29 00:46:00 25 4
gpt4 key购买 nike

我正在对 API 进行 SOAP 调用,这是一个示例响应:

<?xml version="1.0" encoding="utf-8" ?>
<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:body>
<soapenv:fault>
<faultcode>
ERR109
</faultcode>
<faultstring>
Account Expired. Result code is 2163
</faultstring>
<detail>
<ns1:serviceexception xmlns:ns1="http://www.csapi.org/schema/parlayx/common/v2_1">
<messageid>
ERR109
</messageid>
<text>
Account Expired. Result code is 2163
</text>
<variables>
2163
</variables>
</ns1:serviceexception>
</detail>
</soapenv:fault>
</soapenv:body>
</soapenv:envelope>

为了解码这个响应,我构建了一些结构:

type SoapResponse struct {
Body ResponseBody `soapenv:"body"`
}
type ResponseBody struct {
Fault Fault `soapenv:"fault"`
}
type Fault struct {
FaultCode string `xml:"faultcode"`
FaultString string `xml:"faultstring"`
Detail Detail `xml:"detail"`
}
type Detail struct {
ServiceException ServiceException `ns1:"serviceexception"`
}
type ServiceException struct {
ID string `xml:"messageid"`
MessageText string `xml:"text"`
ErrorCode string `xml:"variables"`
}

下面是执行解码部分的代码:

responseBody, _:= ioutil.ReadAll(resp.Body)
var soapResponse = new(SoapResponse)
err := xml.Unmarshal(responseBody, soapResponse)
if err != nil {
panic("Error!")
}

问题是所有 soapResponse 属性都正确填充,除了 soapResponse.Body.Fault.Detail.ServiceException.ID 什么都不打印。
我不知道为什么。任何帮助将不胜感激。

最佳答案

您可以解析具有此类结构的 XML:

type SoapResponse struct {
Body ResponseBody `xml:"soapenv body"`
}
type ResponseBody struct {
Fault Fault `xml:"fault"`
}
type Fault struct {
FaultCode string `xml:"faultcode"`
FaultString string `xml:"faultstring"`
Detail Detail `xml:"detail"`
}
type Detail struct {
ServiceException ServiceException `xml:"serviceexception"`
}
type ServiceException struct {
ID string `xml:"messageid"`
MessageText string `xml:"text"`
ErrorCode string `xml:"variables"`
}

我为第一个元素添加了 namespace 并修复了一些定义。工作示例 - https://play.golang.org/p/vZQhaxYikX

关于go - 在 Go 中解码 SOAP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46592481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com