4.2 mux 使用bug

1. 运行环境#

win10/go 1.19

2. 问题描述?#

  • mux 这段代码可能已经过时

    homeURL, _ := router.Get("home").URL()
    fmt.Println("homeURL: ", homeURL)
  • router.Get 返回的是 * Router,其结构为

    type Route struct {
      // Request handler for the route.
      handler http.Handler
      // If true, this route never matches: it is only used to build URLs.
      buildOnly bool
      // The name used to build URLs.
      name string
      // Error resulted from building a route.
      err error
    
      // "global" reference to all named routes
      namedRoutes map[string]*Route
    
      // config possibly passed in from `Router`
      routeConf
    }

    这里要获取的是 name,可以通过 GetName 方法拿到 Router 的 name,所以应该为

    homeURL := router.Get("home")
    fmt.Println("homeURL:", homeURL.GetName())