I have two yaml files and i want to show the difference between the two. The yaml files are below. I want to display difference between the two yamls.
Like under deletion it should be name:"first" and under updates it should be a full path something like profiles:names:description:"second yaml".
The code below gives me the full object in case of a deeply nested object. How do i get the full path?
YAML1
`
id: 5
name: "first"
repo: "some repo"
profiles:
id: 3
name: default
description: "first yaml"
data:
logs: []
config:
hosts:
url.com: minikube
`
YAML2
`
id: 5
repo: "some repo"
profiles:
id: 3
name: default
description: "second yaml"
data:
logs: []
config:
hosts:
url.com: minikube
`
`
package main
import (
"fmt"
"io/ioutil"
"log"
"reflect"
"gopkg.in/yaml.v3"
)
type Modifications struct {
addition map[string]interface{}
deletion map[string]interface{}
update map[string]interface{}
}
func NewModifications() *Modifications {
var m Modifications
m.addition = make(map[string]interface{})
m.deletion = make(map[string]interface{})
m.update = make(map[string]interface{})
return &m
}
func compareYaml(modifications *Modifications) {
// read file
yfile1, err := ioutil.ReadFile("./old.yaml")
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
yfile2, err := ioutil.ReadFile("./new.yaml")
if err != nil {
log.Fatal(err)
//return
}
// unmarshal ymal
data1 := make(map[string]interface{})
if err := yaml.Unmarshal(yfile1, &data1); err != nil {
fmt.Println(err)
log.Fatal(err)
//return
}
data2 := make(map[string]interface{})
if err := yaml.Unmarshal(yfile2, &data2); err != nil {
fmt.Println(err)
log.Fatal(err)
//return
}
// from this we can iterate the key in data2 then check whether it exists in data1
// if so then we can update the value in data2
// iterate key1 in data2
for key1, value1 := range data1 {
// check whether key1 exists in data2
if _, exists := data2[key1]; exists {
// see if it is an update
if reflect.DeepEqual(data2[key1], value1) {
delete(data2, key1)
} else {
modifications.update[key1] = data2[key1]
delete(data2, key1)
}
} else {
modifications.deletion[key1] = value1
}
}
for k, v := range data2 {
modifications.addition[k] = v
}
}
func main() {
modifications := NewModifications()
compareYaml(modifications)
fmt.Println("************")
fmt.Println("adddition")
fmt.Println(modifications.addition)
fmt.Println("************")
fmt.Println("deletion")
fmt.Println(modifications.deletion)
fmt.Println("************")
fmt.Println("update")
fmt.Println(modifications.update)
fmt.Println("************")
}
`
Playground
You may want to use the compare package:
https://github.com/google/go-cmp
There is a cmp.Diff that allows you to compare two objects and will return the diff in string format.
Related
The hope is to quickly parse a very large number of similar URLs (only one 'id' element differs from one to the next) and dump the response body into a channel that will later be queried by the main function and used to build a text file.
Inside the getpageCanal() function, the body seems to be ok, but after that, I don't understand why the channel doesn't properly load the body string.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
initial := "https://www1.medion.de/downloads/index.pl?op=detail&id="
ending := "&type=treiber&lang=uk"
links := []string{}
os.Remove("dump.txt")
dumpFile, _ := os.Create("dump.txt")
c := make(chan string)
for i := 16000; i < 16004; i++ {
links = append(links, initial+fmt.Sprint(i)+ending)
}
fmt.Println(links[0])
for _, link := range links {
//the hope is to make this a go routine, but first I need to just make it work
getpageCanal(c, link)
}
for el := range c {
fmt.Println(el)
n, err := dumpFile.WriteString(el)
if err != nil {
fmt.Println(err)
}
if n == 0 {
fmt.Println(" nothing written in main")
}
}
}
func getpageCanal(canal chan string, url string) {
defer close(canal)
page, err := http.Get(url)
if err != nil {
fmt.Println("you done fucked up, boy")
}
content, er2 := ioutil.ReadAll(page.Body)
//fmt.Println(content)
if er2 != nil {
fmt.Println(er2)
}
canal <- string(content)
}
After modifying the code as instructed by the first comments (not closing the channel after each call and making the call to the worker function a go routine) I will now provide you with a working version:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
initial := "https://www1.medion.de/downloads/index.pl?op=detail&id="
ending := "&type=treiber&lang=uk"
links := []string{}
os.Remove("dump.txt")
dumpFile, _ := os.Create("dump.txt")
c := make(chan string)
for i := 16000; i < 16004; i++ {
links = append(links, initial+fmt.Sprint(i)+ending)
}
fmt.Println(links[0])
for _, link := range links {
go getpageCanal(c, link)
}
for el := range c {
fmt.Println(el)
n, err := dumpFile.WriteString(el)
if err != nil {
fmt.Println(err)
}
if n == 0 {
fmt.Println(" nothing written in main")
}
}
}
func getpageCanal(canal chan string, url string) {
//defer close(canal)
page, err := http.Get(url)
if err != nil {
fmt.Println("you done fucked up, boy")
}
content, er2 := ioutil.ReadAll(page.Body)
//fmt.Println(content)
if er2 != nil {
fmt.Println(er2)
}
canal <- string(content)
}
I have a struct where one of the fields is a map with the key being another struct. I am using Go version 16.1 and the map created that way is supposedly supported in this version (albeit unsure when field is a map). Here is the relevant code and test that fails with unsupported type error.
package model
import (
"encoding/json"
slog "github.com/go-eden/slf4go"
)
type User struct{
ID string `json:"id" bson:"_id,omitempty"`
FName string `json:"fName"`
MName string `json:"mName"`
LName string `json:"lName"`
Jobs map[*Job]float64 `json:"jobs,omitempty"`
Password string `json:"password"`
IsAdmin bool `json:"isAdmin"`
}
func (u *User)IsModel()bool{
return true
}
func(u * User)ToJSON()string{
//var jsonUser string;
b,err := json.Marshal(u)
if err !=nil {
slog.Info(err)
return err.Error()
}
return string(b)
}
func (u * User)FromJSON(jsonString string)bool{
err := json.Unmarshal([]byte(jsonString),u)
if err != nil{
return false
}
return true
}
and the struct job is:
package model
import "encoding/json"
type Job struct{
ID string `json:"id" bson:"_id,omitempty"`
Name string `json:"name"`
}
func(j *Job)IsModel()bool{
return true
}
func(j *Job) ToJSON()string{
b,err := json.Marshal(j)
if err !=nil {
return err.Error()
}
return string(b)
}
func(j *Job) FromJSON(jsonString string)bool{
err := json.Unmarshal([]byte(jsonString),j)
if err != nil{
return false
}
return true
}
Finally the test that fails is the following (marshalling fails after I add the job to the jobs map):
package model
import (
"fmt"
"reflect"
"testing"
)
func TestUser_ToJSON(t *testing.T) {
user := &User{
ID: "",
FName: "Mike",
MName: "",
LName: "Clovis",
Jobs: make(map[*Job]float64),
Password: "xyz",
IsAdmin: true,
}
newUser := &User{}
fmt.Println(user.ToJSON())
job := &Job{
ID: "1",
Name: "Cashier",
}
user.Jobs[job] = 12.99
fmt.Println("User as json")
fmt.Println(user.ToJSON())
newUser.FromJSON(user.ToJSON())
fmt.Println(newUser)
if reflect.DeepEqual(user,newUser) {
fmt.Println(newUser)
}else{
fmt.Println(user)
fmt.Println(newUser)
t.Error("Cannot marshal and unmarshal User struct")
}
dUser := *user
fmt.Println(dUser)
}
By my reading of the documentation this should work! If anyone has a suggestion or workaround I would appreciate it. As an FYI I have tried making the map with the key being both a job and as a pointer to the job with the same results.
I try to convert a make(map[string]string) into a yaml like that:
Yaml Output desire:
items:
keys1:value1
keys2:value2
keys3:value3
keys4:value4
The keys,values are this listKey map of string. J = string = {"key1":"value1","key2":"value2" }
type Items struct {
items string
ItemsValues map[string][]string
}
func ConvertToYelm(j string){
y := Items{}
var dataJson map[string]string
err := json.Unmarshal([]byte(j), &dataJson)
if err != nil {
fmt.Println(err)
return
}
listKey := make(map[string]string)
for k := range dataJson{
listKey[k] = k
}
yelm, err := yaml.Marshal(listKey)
if err != nil {
fmt.Println(err)
return
}
err = yaml.Unmarshal(yelm, Items)
if err != nil {
fmt.Println(err)
return
}
yeml2, err := yaml.Marshal(&yelm)
fmt.Printf ("%s", string(yeml2))
To be honest, I'm a little bit lost here, thank you for the help
To get the exact YAML from your post:
items:
keys1:value1
keys2:value2
keys3:value3
keys4:value4
You can do this (Go Playground):
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
type ItemsStruct struct {
Items map[string]string `yaml:"items"`
}
func main() {
itms := &ItemsStruct{Items: map[string]string{
"keys1": "value1",
"keys2": "value2",
"keys3": "value3",
"keys4": "value4"}}
yamlBytes, err := yaml.Marshal(itms)
if err != nil {
//handle error
}
fmt.Println(string(yamlBytes))
}
And just to add, I see your code is decoding this JSON {"key1":"value1", "key2":"value2", ... } and then encoding it as YAML in your specified format. Here is the Go Playground for that.
I would like to directly navigate to a value in a map. Lets be more specific with the following go code example which should give me the value of "Walter" directly: (https://play.golang.org/p/tYJsvp39hn)
type Signature struct{
Name string
Signed bool
}
path := "Document.Signatures.1.Name"
map := map[string]interface{}{
"Document": map[string]interface{}{
"Signatures": []interface{}{
Signature{ Name: "Hugo", Signed: false },
Signature{ Name: "Walter", Signed: false },
},
"Otherstuff": "asadwa",
},
"AlsoOtherStuff": "adwaw",
}
// map.giveMe(path)
// even better (if possible:) map.change(path,"ToThisNewValue")
I have searched for solutions, but I can't find any on the internet. Maybe one of you knows how to do this or knows a library to use for me.
Thank you so much in advance!
Quite a lot of reflect calls will be needed if there is no predefined struct.
That being said, you can do it by iterating through the map with type checking on every iteration and handling cases accordingly.
// Splitting the path into keys
keys := strings.Split(path, ".")
var value interface{} = map1
for _, key := range keys {
if value, err = Get(key, value); err != nil {
break
}
}
if err == nil {
fmt.Println("Value:", value)
} else {
fmt.Println("Error:", err)
}
func Get(key string, s interface{}) (v interface{}, err error) {
var (
i int64
ok bool
)
switch s.(type) {
case map[string]interface{}:
if v, ok = s.(map[string]interface{})[key]; !ok {
err = fmt.Errorf("Key not present. [Key:%s]", key)
}
case []interface{}:
if i, err = strconv.ParseInt(key, 10, 64); err == nil {
array := s.([]interface{})
if int(i) < len(array) {
v = array[i]
} else {
err = fmt.Errorf("Index out of bounds. [Index:%d] [Array:%v]", i, array)
}
}
case Signature:
r := reflect.ValueOf(s)
v = reflect.Indirect(r).FieldByName(key)
}
//fmt.Println("Value:", v, " Key:", key, "Error:", err)
return v, err
}
Playground code
How can I get all addresses and masks from local interfaces in golang?
I need the actual network mask configured along with every IP address.
This code does not show the network masks in Windows 7:
package main
import (
"fmt"
"log"
"net"
)
func localAddresses() {
ifaces, err := net.Interfaces()
if err != nil {
log.Print(fmt.Errorf("localAddresses: %v\n", err.Error()))
return
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
log.Print(fmt.Errorf("localAddresses: %v\n", err.Error()))
continue
}
for _, a := range addrs {
log.Printf("%v %v\n", i.Name, a)
}
}
}
func main() {
localAddresses()
}
UPDATE: This issue has been fixed in Go: https://github.com/golang/go/issues/5395
There are multiply types of addresses that a net.Interface might have. The Addr is just an interface which may contain a net.IPAddr. But with a type assertion or type switch you can access the actual address type:
package main
import (
"fmt"
"net"
)
func localAddresses() {
ifaces, err := net.Interfaces()
if err != nil {
fmt.Print(fmt.Errorf("localAddresses: %+v\n", err.Error()))
return
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
fmt.Print(fmt.Errorf("localAddresses: %+v\n", err.Error()))
continue
}
for _, a := range addrs {
switch v := a.(type) {
case *net.IPAddr:
fmt.Printf("%v : %s (%s)\n", i.Name, v, v.IP.DefaultMask())
}
}
}
}
func main() {
localAddresses()
}
Edit
Unfortunately the net package doesn't return the Mask of the address. So, you will have to do the low level syscalls that the net package does. The code below is an example, but parsing of the ip and the mask still needs to be done:
package main
import (
"fmt"
"net"
"os"
"syscall"
"unsafe"
)
func getAdapterList() (*syscall.IpAdapterInfo, error) {
b := make([]byte, 1000)
l := uint32(len(b))
a := (*syscall.IpAdapterInfo)(unsafe.Pointer(&b[0]))
// TODO(mikio): GetAdaptersInfo returns IP_ADAPTER_INFO that
// contains IPv4 address list only. We should use another API
// for fetching IPv6 stuff from the kernel.
err := syscall.GetAdaptersInfo(a, &l)
if err == syscall.ERROR_BUFFER_OVERFLOW {
b = make([]byte, l)
a = (*syscall.IpAdapterInfo)(unsafe.Pointer(&b[0]))
err = syscall.GetAdaptersInfo(a, &l)
}
if err != nil {
return nil, os.NewSyscallError("GetAdaptersInfo", err)
}
return a, nil
}
func localAddresses() error {
ifaces, err := net.Interfaces()
if err != nil {
return err
}
aList, err := getAdapterList()
if err != nil {
return err
}
for _, ifi := range ifaces {
for ai := aList; ai != nil; ai = ai.Next {
index := ai.Index
if ifi.Index == int(index) {
ipl := &ai.IpAddressList
for ; ipl != nil; ipl = ipl.Next {
fmt.Printf("%s: %s (%s)\n", ifi.Name, ipl.IpAddress, ipl.IpMask)
}
}
}
}
return err
}
func main() {
err := localAddresses()
if err != nil {
panic(err)
}
}
Some code shamelessly borrowed from interface_windows.go. Even comments are left intact
I'm modifying #ANisus answer and get all interfaces & masks (tested on Windows 10 & WSL in it (Microsoft Ubuntu 16.04.5 LTS):
package main
import (
"fmt"
"net"
)
func localAddresses() {
ifaces, err := net.Interfaces()
if err != nil {
fmt.Print(fmt.Errorf("localAddresses: %+v\n", err.Error()))
return
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
fmt.Print(fmt.Errorf("localAddresses: %+v\n", err.Error()))
continue
}
for _, a := range addrs {
switch v := a.(type) {
case *net.IPAddr:
fmt.Printf("%v : %s (%s)\n", i.Name, v, v.IP.DefaultMask())
case *net.IPNet:
fmt.Printf("%v : %s [%v/%v]\n", i.Name, v, v.IP, v.Mask)
}
}
}
}
func main() {
localAddresses()
}
This should give you the ipnet you're looking for.
ip, ipnet, err := net.ParseCIDR(a.String())
I know this post for Windows 7, but if you use Mac OS X hope this could help you.
Just Call GetNetMask("en0")
func GetNetMask(deviceName string) string {
switch runtime.GOOS {
case "darwin":
cmd := exec.Command("ipconfig", "getoption", deviceName, "subnet_mask")
out, err := cmd.CombinedOutput()
if err != nil {
return ""
}
nm := strings.Replace(string(out), "\n", "", -1)
log.Println("netmask=", nm, " OS=", runtime.GOOS)
return nm
default:
return ""
}
return ""
}