I have Go program that has a function defined. I also have a map that should have a key for each function. How can I do that?
I have tried this, but this doesn\'t wo
Here is the way I made it work in my case:
package main
import (
"fmt"
)
var routes map[string]func() string
func main() {
routes = map[string]func() string{
"GET /": homePage,
"GET /about": aboutPage,
}
fmt.Println("GET /", pageContent("GET /"))
fmt.Println("GET /about", pageContent("GET /about"))
fmt.Println("GET /unknown", pageContent("GET /unknown"))
// Output:
// GET / Home page
// GET /about About page
// GET /unknown 404: Page Not Found
}
func pageContent(route string) string {
page, ok := routes[route]
if ok {
return page()
} else {
return notFoundPage()
}
}
func homePage() string {
return "Home page"
}
func aboutPage() string {
return "About page"
}
func notFoundPage() string {
return "404: Page Not Found"
}
https://play.golang.org/p/8_g6Di1OKZS