'Parsing structured data in golang
I have a well-formatted byte array that has rows and columns as follows (note that the columns are separated by spaces). The column names and order are guaranteed:
NAME UUID TYPE DEVICE
WAN 6a62d79f-fba2-45b3-a3dd-e847c4706d96 ethernet ens18
DMZ 46a55117-b545-407e-af6e-25d48dfe95f5 ethernet ens21
LAN 1691607b-9b73-46ff-95c4-9652d062706a ethernet ens19
MGT a4819491-243c-4e5b-8cef-a49de5a9cb07 ethernet ens22
Untrusted 0734a0ea-c242-4333-bece-2b5cb16e3337 ethernet ens20
I would like to iterate over each row and populate a structure as follows:
type Device struct {
connectionID string
uuid string
deviceType string
deviceName string
}
What is the best way to approach this?
Solution 1:[1]
I thought I would add the code for the comment I wrote above:
type Device struct {
connectionID string
uuid string
deviceType string
deviceName string
}
type Devices []Device
// getNetworkConnections retrieves a list of network connections and their associated details.
// Details include: connection name, uuid, type, and device id (aka NIC name).
func getNetworkConnections() Devices {
nmcliCmd := exec.Command("nmcli", "con", "show")
cmdOutput, err := nmcliCmd.Output()
if err != nil {
log.Fatal(err)
}
// Iterate through the devices and populate the type.
var device Device
rows := strings.Split(string(cmdOutput[:]), "\n") // Create an array of rows containing the output
for _, row := range rows[1:] { // Skip the heading row and iterate through the remaining rows
cols := strings.Fields(row) // Extract each column from the row.
if len(cols) == 4 {
device.connectionID = cols[0]
device.uuid = cols[1]
device.deviceType = cols[2]
device.deviceName = cols[3]
devices = append(devices, device)
}
}
return devices
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bryon |
