I'm using reflection to do this:
method_name := CommandMap[command]
thing := reflect.ValueOf(self).MethodByName(method_name)
thing_s := fmt.Sprintf("%s", thing)
if thing_s == "<invalid reflect.Value>" {
self.writeMessage(550, "not allowed")
} else {
thing.Call([]reflect.Value{})
}
but there must be a better way. The point of the above code was to get rid of:
if command == "this" {
runThis()
} else if command == "that" {
runThat()
} etc. etc.
I want to not have a big if else tree. This is an ftp server http://github.com/andrewarrow/paradise_ftp and I need to handle 15 or so commands like "USER" and "PASS" and "QUIT" etc. etc. I want each one to call a method like "handleUser" or "handlePass". But using reflection is a bad idea. It's too slow.
From your linked use case, it appears that having a map of strings to functions will work best. Example:
func MakeCommandMap() map[string]func(*Paradise) {
m := map[string]func(*Paradise){
"USER": (*Paradise).HandleUser,
"PASS": (*Paradise).HandlePass,
}
// ...
return m
}
Calling the functions:
name := "USER"
if fn := m[name]; fn != nil {
fn(self) // where self is *Paradise
}