Skip to content

Instantly share code, notes, and snippets.

@hirose31
Last active September 7, 2018 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirose31/c926ffe2dc25c45a4330092488785257 to your computer and use it in GitHub Desktop.
Save hirose31/c926ffe2dc25c45a4330092488785257 to your computer and use it in GitHub Desktop.
nested map

お題

こういうデータを処理して

eth0
  link/ether 00:00:00:00:00:00
  inet 192.168.0.1 brd 192.168.0.255
eth1
  link/ether 11:11:11:11:11:11
  inet 192.168.1.1 brd 192.168.1.255

こういう構造のmap的なものに格納したい。

{
  "network": {
    "interfaces": {
      "eth0": {
        "addresses": {
          "00:00:00:00:00:00": {
            "family": "lladdr"
          },
          "192.168.0.1": {
            "broadcast": "192.168.0.255",
            "family": "inet"
          }
        }
      },
      "eth1": {
        "addresses": {
          "11:11:11:11:11:11": {
            "family": "lladdr"
          },
          "192.168.1.1": {
            "broadcast": "192.168.1.255",
            "family": "inet"
          }
        }
      }
    }
  }
}

イメージ

package main

import (
	"fmt"

	simplejson "github.com/bitly/go-simplejson"
)

func main() {
	data := []string{
		"eth0",
		"  link/ether 00:00:00:00:00:00",
		"  inet 192.168.0.1 brd 192.168.0.255",
		"eth1",
		"  link/ether 11:11:11:11:11:11",
		"  inet 192.168.1.1 brd 192.168.1.255",
	}

	network := ...
	// がんばる!

	sj := simplejson.New()
	sj.Set("network", network)
	json, _ := sj.EncodePretty()
	fmt.Printf("%s\n", string(json))
}
// @hirose31
// objects を使ってみた。
package main
import (
"fmt"
"regexp"
simplejson "github.com/bitly/go-simplejson"
"github.com/stretchr/stew/objects"
)
func main() {
data := []string{
"eth0",
" link/ether 00:00:00:00:00:00",
" inet 192.168.0.1 brd 192.168.0.255",
"eth1",
" link/ether 11:11:11:11:11:11",
" inet 192.168.1.1 brd 192.168.1.255",
}
objects.PathSeparator = "/"
network := objects.M(
"interfaces", objects.M(),
)
ifname := ""
splitter := regexp.MustCompile(`\s+`)
for _, line := range data {
e := splitter.Split(line, -1)
if e[0] != "" {
ifname = e[0]
} else if e[1] == "link/ether" {
addr := e[2]
keypath := fmt.Sprintf("interfaces/%s/addresses/%s", ifname, addr)
network.Set(keypath, objects.M(
"family", "lladdr",
))
} else if e[1] == "inet" {
addr := e[2]
keypath := fmt.Sprintf("interfaces/%s/addresses/%s", ifname, addr)
brd := ""
for i, v := range e {
if v == "brd" {
brd = e[i+1]
}
}
network.Set(keypath, objects.M(
"family", "inet",
"broadcast", brd,
))
}
}
sj := simplejson.New()
sj.Set("network", network)
json, _ := sj.EncodePretty()
fmt.Printf("%s\n", string(json))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment