Problem with Goapp being used for product to gather information

I wrote an app (my first of anything ever written in golang) and i’m having some problem. The tl;dr is, i’m using a generated swagger spec to pull information from a product we use here at work (a rapid7 product). It works great on one of our instances, but another, i’m getting an error:

	panic: runtime error: index out of range

	goroutine 1 [running]:
	main.ToCsv(0x0, 0x0, 0x0, 0x13451c0, 0xc4202a0030)
	        /Users/test/workspace/GoLangIVMCollector/InsightVM_Data.go:307 +0xc63
	main.main()
	        /Users/test/workspace/GoLangIVMCollector/InsightVM_Data.go:475 +0xe39

So i think (and i can post the rest if necessary) this is the code necessary to troubleshoot:

func ToCsv(inputs []interface{}, output io.Writer) {
	w := csv.NewWriter(output)
	defer w.Flush()

	// Get Header
	r := reflect.ValueOf(inputs[0])
	val := reflect.Indirect(reflect.ValueOf(inputs[0]))
	var headers []string
	for i := 0; i < r.NumField(); i++ {
		headers = append(headers, val.Type().Field(i).Name)
	}
	w.Write(headers)

	// Get Content
	for _, input := range inputs {
		ri := reflect.ValueOf(input)

		var result []string
		for i := 0; i < ri.NumField(); i++ {
			switch ri.Field(i).Interface().(type) {
			case bool:
				result = append(result, strconv.FormatBool(ri.Field(i).Interface().(bool)))
			case int32:
				result = append(result, strconv.FormatInt(int64(ri.Field(i).Interface().(int32)), 10))
			case string:
				result = append(result, ri.Field(i).Interface().(string))
			default:
				result = append(result, "")
			}
		}
		w.Write(result)
	}
}

And here is the other function that uses this:

	// Reports
	reports, err := GetAllReports(r7vm)
	var structuredReports []interface{}

	if err != nil {
		log.Fatal(fmt.Sprintf("Failed to retrieve reports: %s", err))
	} else {
		fmt.Println("Gathering Report Information...")
		for _, report := range reports {
			structuredReports = append(structuredReports, structs.CreateReport(report))
		}

		file, _ := os.Create(fmt.Sprintf("%sreports.csv", dir))
		defer file.Close()
		ToCsv(structuredReports, file)
	}

The error is occurring on the line (307 in the initial error above)

r := reflect.ValueOf(inputs[0])

and the second error is because i’m using that ToCSV function at the bottom of the 2nd codeblock above. The JSON i’m pulling back is linked here https://pastebin.com/m7SGiaYV

tl;dr making a call to an api, getting the above json returned, trying to put it in a csv using a function linked above, getting the error above. Please let me know if anymore information is needed.

EDIT: Just tried to simply print the results of the pull to the console, and i’m getting nothing. I think this has something to do with how i’m paging the results back or something

Is this line 307 of InsightVM_Data.go?

I assume that your inputs is empty and therefore you can’t access element 0. Please do a length check first.

1 Like

hello