Trying to parse some nmap data with golang, but the layout of my structs isn't quite working. Link to code on playground: https://play.golang.org/p/kODRGiH71W
package main
import (
"encoding/xml"
"fmt"
)
type Extrareasons struct {
Reason string `xml:"reason,attr"`
Count uint32 `xml:"count,attr"`
}
type Extraports struct {
State string `xml:"state,attr"`
Count uint32 `xml:"count,attr"`
Reason Extrareasons `xml:"extrareasons"`
}
type StateProps struct {
State string `xml:"state,attr"`
Reason string `xml:"reason,attr"`
}
type PortProps struct {
Protocol string `xml:"protocol,attr"`
Port uint32 `xml:"portid,attr"`
StateStuff StateProps `xml:"state"`
}
type PortInfo struct {
Extra Extraports `xml:"extraports"`
PortProp PortProps `xml:"port"`
}
type Ports struct {
Port PortInfo `xml:"ports"`
}
func main() {
xmlString := `<ports>
<extraports state="closed" count="64">
<extrareasons reason="conn-refused" count="64" />
</extraports>
<port protocol="tcp" portid="22">
<state state="open" reason="syn-ack" reason_ttl="0" />
<service name="ssh" method="table" conf="3" />
</port>
</ports>`
var x Ports
if err := xml.Unmarshal([]byte(xmlString), &x); err == nil {
fmt.Printf("%+v
", x)
} else {
fmt.Println("err:", err)
}
}
$ go run test.go
{Port:{Extra:{State: Count:0 Reason:{Reason: Count:0}} PortProp:{Protocol: Port:0 StateStuff:{State: Reason:}}}}
The layer that the Ports
wrapper struct creates is unnecessary, drop it. You only need to model the contents of the root xml element which is <ports>
and its content is described / modeled by PortInfo
. There is no need for a type that wraps the root element.
Simply change
var x Ports
to
var x PortInfo
And it will work. Try it on the Go Playground. Output (wrapped):
{Extra:{State:closed Count:64 Reason:{Reason:conn-refused Count:64}}
PortProp:{Protocol:tcp Port:22 StateStuff:{State:open Reason:syn-ack}}}