There is a thoroughly explained example of using the http package here:
http://golang.org/doc/codelab/wiki/
Andrew
The only choice is to build an explicit map from string
to function handler and then iterate over it, or something
similar. With a short script, you could generate that
code as part of your build process instead of maintaining
it by hand.
Russ
"func() int" is the type of functions which take no arguments and which
return an int. As another example I'll use a "func(string, string)
string" in the following code.
package main
import (
"fmt"
)
type Fn func(string, string) string
func secondThenFirst(first, second string) string {
return fmt.Sprintf("%s %s", second, first)
}
func main() {
var f Fn = secondThenFirst
fmt.Printf(f("world\n", "hello"))
}
---
> Here is the example that I threw together, which fails. Please
> correct:
<< snip >>
Hopefully this is illustrative for you:
package main
import (
"fmt"
)
type Fn func()
type FnMap map[string] Fn
func test0() {
fmt.Printf("called test0\n")
}
func test1() {
fmt.Printf("called test1\n")
}
func main() {
fns := make( FnMap )
fns["test0"] = test0
fns["test1"] = test1
fns["test1"]()
fns["test0"]()
}
one way to do this kind of thing is to have a central
registry of functions and have each module call a Register
function at init time.
for instance:
// main.go
package main
var handlers = make(map[string]interface{})
func RegisterHandler(s string, h interface{}){
handlers[s] = h
}
// page1.go
package main
func init() {
RegisterHandler("page1", page1handler)
}
func page1handler(s string){
}
// someotherpage.go
....
for i := 0; i < 10; i++ {
s := fmt.Sprintf("page%d", i)
web.Get("/" + s, handlers[s])
}
hope this helps.
PS FWIW, i don't think i'm keen on the way that web.go uses dynamically
typed handlers. i like to see what kind of function is expected as an argument;
i don't think it would be too hard to do.