samedi 26 mars 2016

Convert string value to function call

I want to specify a function based on a string. I'm getting strings out of a map, in the example below they are the values in function while interating ove the map. Now for example, when the string value function == "networkInfo", I would like to "treat" that value as a real functions' name. It's hard to explain, but I think you guys will know what I mean.

My goal is to remove the switch statement and directly call c.AddFunc(spec, func() { networkInfo() }) where networkInfo is the function name, extracted from string function. I know this is possible, but I don't know how :(. Help is appreciated!

// ScheduleCronjobs starts the scheduler
func ScheduleCronjobs() {

tasks := props.P.GetStringMapString("tasks")
log.Infof("number of tasks: %d", len(tasks))

if len(tasks) != 0 {
    c := cron.New()

    // for each task, initialize
    for function, spec := range tasks {
        switch function {
        case "networkInfo":
            c.AddFunc(spec, func() { networkInfo() })
        case "bla":
            c.AddFunc(spec, func() { bla() })
        default:
            log.Errorf("unknown task: %q", function)
        }
    }
    c.Start()
}

// after initialization, send out confirmation message
slack.SendMessage("tasks initialized", props.P.GetString("channel"))
}





Aucun commentaire:

Enregistrer un commentaire