rveen / ogdl

OGDL for Go
BSD 2-Clause "Simplified" License
37 stars 10 forks source link

wishlist: Support an encoding/* style "decode into a struct / encode a struct" api #2

Open tv42 opened 10 years ago

tv42 commented 10 years ago

I wish I had an OGDL library that looked like everything else under encoding/*.

Yes, it'll lose information, and can't round-trip all OGDL data. But it's way more convenient to use than needing to run "queries" on a thing on every access, or writing a function that runs all those queries and returns a struct with the results..

Think of it as ogdl.Graph being the moral equivalent of decoding JSON to interface{}. Used when you know you need to round-trip, but otherwise painful.

It could use struct tags in a way vary similar to encoding/xml, and allow the user to put ogdl paths in them. Something like

network
  eth0
    ip   192.168.0.10
    mask 255.255.255.0
    gw   192.168.0.1

hostname crispin
nameserver 8.8.8.8
nameserver 8.8.4.4
type Config struct {
    Hostname string
    // decoding to a map type knows that the subgraph should be >=2
    // levels deep, first level becomes the keys
    Network map[string]*Interface
    // decoding to a slice value appends every matching subgraph
    Nameserver []net.IP
}

type Interface struct {
    IP      net.IP `ogdl:"ip"`
    Netmask net.IP `ogdl:"mask"`
    Gateway net.IP `ogdl:"gw"`
}

And naturally each field would use encoding/text to actually parse the string. And if the value isn't a string but a subgraph, you could see if the field has a UnmarshalOGDL / MarshalOGDL method, just like JSON; the input to such unmarshal would be a Graph, not []byte.

Even more ideally, this would tie into a streaming parser and avoid holding the graph in memory all at once. And the above UnmarshalOGDL could tie into EventHandler or Parser somehow, too.

tv42 commented 10 years ago

And an example of OGDL paths in struct tag would be something like

noise
  goodstuff 42
type T struct {
    Value int `ogdl:"noise.goodstuff"`
}
rveen commented 10 years ago

Your wish is totally justified. Hǎiliàng Wang has started working in that direction.