我有一个结构作为键,func作为值的地图,我想在检索给定键的值时调用func
map[struct]func
map[
{contact %!s(int=1)}:%!s(main.Controller=0x4c7b50)
{services/basket %!s(int=2)}:%!s(main.Controller=0x4c7ad0)
{categories %!s(int=1)}:%!s(main.Controller=0x4c7ae0)
{categories/{category} %!s(int=2)}:%!s(main.Controller=0x4c7af0)
{categories/{category}/{product} %!s(int=3)}:%!s(main.Controller=0x4c7b00)
{basket %!s(int=1)}:%!s(main.Controller=0x4c7b10)
{checkout %!s(int=1)}:%!s(main.Controller=0x4c7b40)
{sitemap %!s(int=1)}:%!s(main.Controller=0x4c7b30)
{services/order %!s(int=2)}:%!s(main.Controller=0x4c7ac0)
{services/image %!s(int=2)}:%!s(main.Controller=0x4c7b20)
{/ %!s(int=1)}:%!s(main.Controller=0x4c7a00)
]
c := RouteMap[struct]
如果我fmt.Printf("%s", c)
我得到了内存地址,我如何在地址处调用func?
我尝试了c(),但这会产生运行时错误:
%s
0x4c7b10%s
<nil>panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x4c76f4]
goroutine 5 [running]:
main.RequestHandler(0x577ce0, 0xc042004018)
C:/Users/mon/Desktop/server.go:91 +0x684
created by main.main
C:/Users/mon/Desktop/server.go:41 +0x2a0
示例
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"strings"
"time"
)
var RouteMap = make(map[PathIdentifier]Controller)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
}
MapRoute("/", HomeController)
MapRoute("categories", CategoriesController)
MapRoute("categories/{category}", CategoryController)
MapRoute("categories/{category}/{product}", CategoryProductController)
MapRoute("basket", BasketController)
MapRoute("checkout", CheckoutController)
MapRoute("sitemap", SitemapController)
MapRoute("contact", ContactController)
MapRoute("services/order", OrderServiceController)
MapRoute("services/basket", BasketServiceController)
MapRoute("services/image", ImageServiceController)
fmt.Printf("%s\n", RouteMap)
for {
conn, err := ln.Accept()
if err != nil {
// handle error
}
go RequestHandler(conn)
}
}
// ----------------------- Request & Response ---------------------------
func ParseQueryString() {}
func ParsePostData() {}
func ResponseHeaders() {}
func ParseRequestHeaders() {}
func RequestHandler(conn net.Conn) {
CrLf := "\r\n"
Terminator := CrLf + CrLf
defer func() {
//fmt.Println("Closing connection...")
conn.Close()
}()
timeoutDuration := 10 * time.Second
bufReader := bufio.NewReader(conn)
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
requestBytes, err := bufReader.ReadBytes('\n')
if err != nil {
fmt.Println(err)
return
}
requestTokens := bytes.Split(requestBytes, []byte(" "))
requestMethod := string(requestTokens[0])
requestPath := string(requestTokens[1])
//requestHTTPVersion := string(requestTokens[2])
if requestMethod == "GET" {
// Parse path
pathTokens := strings.Split(requestPath, "/")
segments := len(pathTokens)
key := PathIdentifier{path: "categories/{category}/{product}", segments: (segments - 1)}
c := RouteMap[key]
fmt.Print("%s\n", c)
}
document := []byte("HTTP/1.1 200 OK" + CrLf + "Date: Mon, 27 Jul 2009 12:28:53 GMT" + CrLf + "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT" + CrLf + "Content-Length: 49" + CrLf + "Content-Type: text/html" + CrLf + "Connection: Closed" + Terminator + "<html><body><h1>Hello, World!</h1></body></html>" + Terminator)
conn.Write(document)
}
// ----------------------------- Controller -----------------------------
type Controller func()
type PathIdentifier struct {
path string
segments int
}
func MapRoute(view string, controller Controller) {
if controller != nil {
if view != "/" {
pathTokens := strings.Split(view, "/")
key := PathIdentifier{path: view, segments: len(pathTokens)}
RouteMap[key] = controller
return
}
key := PathIdentifier{path: view, segments: 1}
RouteMap[key] = controller
}
}
func HomeController() {
fmt.Print("Invoking the HomeController.\n")
}
func OrderServiceController() {
}
func BasketServiceController() {
}
func CategoriesController() {
}
func CategoryController() {
}
func CategoryProductsController() {
}
func CategoryProductController() {
}
func BasketController() {
}
func ImageServiceController() {
}
func SitemapController() {
}
func CheckoutController() {
}
func ContactController() {
}
答案 0 :(得分:1)
我不确定你是否需要通过地址&#34;来呼叫它。当您通过将其作为变量传递进行调用时,编译器会为您执行此操作&#34; under-the-hood&#34;。取其地址并调用它。
如果你希望某种程度的间接,你可以:
M := map[string]func()
M["function 1"] = F
// and then call them from map like
M["function 1"]()