我正在尝试在 Go 中构建一个简单的路由器,我在结构上有一个 get 方法,该方法应该将回调传递给以 url 为键的 Get 路由映射,它似乎fmt.Println(urlCallback)返回 nil 值并导致运行时恐慌如果我试图调用它,来自 javascript 背景,我只是开始掌握指针之类的东西,并且觉得它可能与此有关,如果有人能告诉我为什么传递的 func 为零,那就太好了.
这是我的“路由器”包。
package Router
import (
"fmt"
"net/http"
"net/url"
"log"
)
type Res http.ResponseWriter
type Req *http.Request
type RouteMap map[*url.URL]func(Res, Req)
type MethodMap map[string]RouteMap
type Router struct {
Methods MethodMap
}
func (router *Router) Get(urlString string, callback func(Res, Req)) {
parsedUrl, err := url.Parse(urlString)
if(err != nil) {
panic(err)
}
fmt.Println(parsedUrl)
router.Methods["GET"][parsedUrl] = callback
}
func (router *Router) initMaps() {
router.Methods = MethodMap{}
router.Methods["GET"] = RouteMap{}
}
func (router Router) determineHandler(res http.ResponseWriter, req *http.Request) {
fmt.Println(req.URL)
fmt.Println(req.Method)
methodMap := router.Methods[req.Method]
urlCallback := methodMap[req.URL]
fmt.Println(methodMap)
fmt.Println(urlCallback)
}
func (router Router) Serve(host string, port string) {
fullHost := host + ":" + port
fmt.Println("Router is now serving to:" + fullHost)
http.HandleFunc("/", router.determineHandler)
err := http.ListenAndServe(fullHost, nil)
if err == nil {
fmt.Println("Router is now serving to:" + fullHost)
} else {
fmt.Println("An error occurred")
log.Fatal(err)
}
}
func NewRouter() Router {
newRouter := Router{}
newRouter.initMaps()
return newRouter
}
和我的主要。
package main
import (
"./router"
"fmt"
)
func main() {
router := Router.NewRouter()
router.Get("/test", func(Router.Res, Router.Req) {
fmt.Println("In test woohooo!")
})
router.Serve("localhost", "8888")
}
动漫人物
相关分类