Populate values for Go struct

Folks,
I have following struct and I want to populate with values, when I run it gives me error maybe my values are not correct

package main
import (
 "fmt"
 "os"
 "strings"
 "bufio"
)

func main() {
// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter BIG-IP Management IP: ")
bigip_mgmt, _ := reader.ReadString('\n')
fmt.Print("Enter username for BIG-IP: ")
user, _ := reader.ReadString('\n')
fmt.Print("Enter password  for BIG-IP: ")
pass, _ := reader.ReadString('\n')
fmt.Print("Enter IPFIX Pool  for BIG-IP: ")
Ipfix_pool, _ := reader.ReadString('\n')

// Trim whitespace and print
fmt.Printf("Bigip Management is: \"%s\", Bigip username : \"%s\", Bigip pass : \"%s\", Bigip IPFIX Pool \"%s\"\n",
  strings.TrimSpace(bigip_mgmt), strings.TrimSpace(user), strings.TrimSpace(pass), strings.TrimSpace(ipfix_pool))
fmt.Printf(bigip_mgmt)
 create := createipfx()
 fmt.Println(create)
}
func createipfx() string {
  type Payload struct {
  	Name    string `json:"name"`
  	Monitor string `json:"monitor"`
  	Members []struct {
  		Name    string `json:"name"`
  		Address string `json:"address"`
  	} `json:"members"`
  }
  data := Payload{
  // fill struct
   Name: "FirstIPFIXPool",
   Monitor: "gateway_icmp ",
   Members: Members[]{
     {
     Name: Ipfix_pool:4739,
     Address: Ipfix_pool,
   },
   },
  }
  fmt.Println(data)
  payloadBytes, err := json.Marshal(data)
  if err != nil {
  	// handle err
  }
  body := bytes.NewReader(payloadBytes)

  req, err := http.NewRequest("POST", os.ExpandEnv("https://bigip_mgmt/mgmt/tm/ltm/pool"), body)
  if err != nil {
  	// handle err
  }
  req.SetBasicAuth(user, pass)
  req.Header.Set("Content-Type", "application/json")

  resp, err := http.DefaultClient.Do(req)
  if err != nil {
  	// handle err
  }
  defer resp.Body.Close()
  return "Created ipfix pool"

}

when I run it gives me error saying syntax error, maybe my Go struct values are not correct

o run ipfix_deploy.go

command-line-arguments

./ipfix_deploy.go:43:21: syntax error: unexpected ], expecting expression
./ipfix_deploy.go:44:6: syntax error: unexpected {, expecting expression
./ipfix_deploy.go:45:6: syntax error: unexpected Name, expecting ]
./ipfix_deploy.go:48:4: syntax error: unexpected }, expecting expression
./ipfix_deploy.go:49:3: syntax error: unexpected }, expecting expression

Please use the code formatting function of the forum or, better, post your example to play.golang.org.

1 Like

You should use double quotes, but this is probably just one of the errors.

No, '\n' is fine. ReadString takes a byte as its argument, which a rune can be coerced into, but a string can’t, so single quotes here.

I’d guess its related to the Members: Members[]{...} on line 42.

  1. Members is not a defined struct.
  2. Members (the struct field) takes an []struct{…}

After I have fixed this with:

Members: []struct {
Name string `json:"name"`
Address string `json:"address"`
}{
{
Name: "Ipfix_pool:4739",
Address: "Ipfix_pool",
},
},

I do get another error because of ipfix_pool not beeing defined on line 24. Fixing it by simple renaming ipfix_pool to Ipfix_pool then causes the next errors:

prog.go:53:22: undefined: json
prog.go:57:9: undefined: bytes
prog.go:59:13: undefined: http
prog.go:63:18: undefined: user
prog.go:63:24: undefined: pass
prog.go:66:14: undefined: http

Which I can mostly fix by adding to the import statement:

import (
  ...
  "encoding/json"
  "bytes"
  "net/http"
)

Still those 2 remain:

prog.go:66:18: undefined: user
prog.go:66:24: undefined: pass

I will not dig into this. I leave those to the OP.

PS: A link to the playground with my current results: https://play.golang.org/p/zSNoyD_DsGa

I copy pasted this to playground and it reported error, but I see now that normal single quotes are actually replaced with some other kind here in the post (’ and ') :smiley: And didn’t look at the signature at all.

Yeah, thats why I actually read the error messages when I paste into playground. Also did this quite a few times already, such that I’m used to replacing mangled quotes.

Thank you @NobbZ I made changes and now there is this one error prog.go:46:12: missing type in composite literal

package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func main() {
	// Create a single reader which can be called multiple times
	reader := bufio.NewReader(os.Stdin)
	// Prompt and read
	fmt.Print("Enter BIG-IP Management IP: ")
	bigip_mgmt, _ := reader.ReadString('\n')
	fmt.Print("Enter username for BIG-IP: ")
	user, _ := reader.ReadString('\n')
	fmt.Print("Enter password  for BIG-IP: ")
	pass, _ := reader.ReadString('\n')
	fmt.Print("Enter IPFIX Pool  for BIG-IP: ")
	Ipfix_pool, _ := reader.ReadString('\n')

	// Trim whitespace and print
	fmt.Printf("Bigip Management is: \"%s\", Bigip username : \"%s\", Bigip pass : \"%s\", Bigip IPFIX Pool \"%s\"\n",
		strings.TrimSpace(bigip_mgmt), strings.TrimSpace(user), strings.TrimSpace(pass), strings.TrimSpace(Ipfix_pool))
	fmt.Printf(bigip_mgmt)
	create := createipfx()
	fmt.Println(create)
}

func createipfx() string {
	type Payload struct {
		Name    string `json:"name"`
		Monitor string `json:"monitor"`
		Members []struct {
			Name    string `json:"name"`
			Address string `json:"address"`
		} `json:"members"`
	}
	data := Payload{
		// fill struct
		Name:    "FirstIPFIXPool",
		Monitor: "gateway_icmp ",
		Members: {
			{
				Name:    "Ipfix_pool:4739",
				Address: "Ipfix_pool",
			},
		},
	}
	fmt.Println(data)
	payloadBytes, err := json.Marshal(data)
	if err != nil {
		// handle err
	}
	body := bytes.NewReader(payloadBytes)

	req, err := http.NewRequest("POST", os.ExpandEnv("https://bigip_mgmt/mgmt/tm/ltm/pool"), body)
	if err != nil {
		// handle err
	}
	req.SetBasicAuth("user", "pass")
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		// handle err
	}
	defer resp.Body.Close()
	return "Created ipfix pool"

}

Can you please do us a favour and format your code correctly by enclosing it in triple-backticks, markdown style fenced codeblock?

It will make the code much easier to read and especially to copy, since quotes will remain proper quotes then.

I refuse to fix those again…

@NobbZ done, I think its giving missing type in composite literal error at

   Members: {
     {
       Name:    "Ipfix_pool:4739",
       Address: "Ipfix_pool",
     },
   },

Please take a close look into how I fixed this. You need to copy the anonymous structure declaration from the surrounding strict.

		Members: []struct {
			Name    string `json:"name"`
			Address string `json:"address"`
		}{
			{
				Name:    "Ipfix_pool:4739",
				Address: "Ipfix_pool",
			},
		},

@NobbZ Worked !! thank you very much

In my opinion it’s easier to extract a proper type for that field instead of inclining an anonymous struct.

1 Like

@NobbZ thanks however I am getting panic runtime error now after I entered all the values

SJC-ML-SHITOLE:tetration shitole$ go run ipfix_deploy.go
Enter BIG-IP Management IP: 10.192.74.73
Enter username for BIG-IP: admin
Enter password  for BIG-IP: admin
Enter IPFIX Pool  for BIG-IP: 15.1.1.1
Bigip Management is: "10.192.74.73", Bigip username : "admin", Bigip pass : "admin", Bigip IPFIX Pool "15.1.1.1"
10.192.74.73
value of data {Name:FirstIPFIXPool Monitor:gateway_icmp  Members:[{Name:Ipfix_pool:4739 Address:Ipfix_pool}]}panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x11fc67d]

goroutine 1 [running]:
main.createipfx(0x0, 0x0)
	/Users/shitole/tetration/ipfix_deploy.go:75 +0x38d
main.main()
	/Users/shitole/tetration/ipfix_deploy.go:30 +0x58e
exit status 2

Are you still running the same code thats on the playground?

That one that does only have // handle error here comments? Please replace those with proper error handling, create a playground or gist wich contains proper code. But perhaps you’ll already find the problem when you introduce error handling, as my guess is that you haven’t set up the connection right or weren’t able to connect to the host or something like that.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.