I need to read data from XML file and convert that into a function in golang. Because in golang I need this function to be used in mux.NewRouter().HandleFunc("/url",functionName). I need a way to convert this string which read from XML file to a function name to use as functionName.
Asked
Active
Viewed 178 times
0
-
1Only possible with some kind of registry. Possible duplicate of [Call all functions with special prefix or suffix in Golang](https://stackoverflow.com/questions/37384473/call-all-functions-with-special-prefix-or-suffix-in-golang/37384665#37384665). – icza Jun 01 '17 at 13:53
-
1The typical way I see this done is to generate a `map[string]func()` during init or setup. Downside, however, is that all of the functions need to have the same signature (though this would arguably already be a requirement, if where you're calling these functions isn't supposed to know even their names). If you need differing signatures, you'll need a `switch` or similar. – Kaedys Jun 01 '17 at 15:23
1 Answers
0
If you register all the functions that you want to call as methods on a type then you can do something like the following.
type Foo struct{}
func (Foo) Bar() {
fmt.Println("foobar")
}
...
f := reflect.ValueOf(Foo{}).MethodByName("Bar").Interface().(func())
f()
Where you reflect the struct that the methods are on and then get the method's interface value and type assert it back to it's func signature.
Runnable example: https://play.golang.org/p/m2nywmeD0Y

Zak
- 5,515
- 21
- 33