Returning data from function call


(Gavin Mc Kee) #1

Hi,

I’m trying to learn go and I’ve written a function that snmp polls (either a single device or n devices).

How do I return values to the main function for each getDevices call? What is the best practice?

func main() {

	var cfg Config
	cfgFile := flag.String("config", "config.json", "configuration file")
	flag.Parse()

	data, err := ioutil.ReadFile(*cfgFile)
	if err != nil {
		log.Fatal("couldn't read configuration file ", *cfgFile)
	}
	log.Println(string(data))
	err = json.Unmarshal(data, &cfg)
	if err != nil {
		log.Fatal("Error parsing configuration ", err.Error())

	}

	fmt.Println(cfg.DevListUrl)
	devices := getDevices(&cfg)


	for _, dev := range devices {
		wg.Add(1)
		go getSysInfo(dev, &cfg)
	}
	wg.Wait()


func getSysInfo(device snmpHostConfig, cfg *Config) {

	log.Println("Polling...", device.Hostname)

	params := &gosnmp.GoSNMP{
		Target:    device.Ip,
		Port:      161,
		Community: cfg.SnmpCommunity,
		Version:   gosnmp.Version2c,
		Timeout:   time.Duration(2) * time.Second,
		//Logger:    log.New(os.Stdout, "", 0),
	}

	err := params.Connect()

	if err != nil {
		log.Fatalf("Connect() err: %v", err)
	}

	defer params.Conn.Close()

	//oids := []string{".1.3.6.1.2.1.1.5.0", ".1.3.6.1.2.1.1.1.0"}
	oids := make([]string,len(systemOids))
	onames:=make([]string,len(systemOids))
	i:=0
	for k,v :=range systemOids{
		oids[i]=v
		onames[i]=k
		i++
	}

	if result, err := params.Get(oids); err == nil {
		for i, variable := range result.Variables {
			//sysinfo := new(systemInfo)

			//fmt.Printf("%d: oid: %s ", i, variable.Name)
			oidName := onames[i]
			// the Value of each variable returned by Get() implements
			// interface{}. You could do a type switch...
			switch variable.Type {
			case gosnmp.OctetString:
				//sysinfo.info[oidName] = string(variable.Value.([]byte))
				fmt.Printf("%s string: %s\n", oidName, string(variable.Value.([]byte)))

			default:
				// ... or often you're just interested in numeric values.
				// ToBigInt() will return the Value as a BigInt, for plugging
				// into your calculations.
				fmt.Printf("number: %d\n", gosnmp.ToBigInt(variable.Value))
			}

		}
		} else {
			log.Println("Failed to gather system information from", device.Hostname)
		}
	wg.Done()

}

(Jakob Borg) #2

Typically, use a channel. The guide has some examples and there is a good blog post also on the subject.


(system) #3

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