【问题标题】:Dynamically add routes in golang httpgolang http中动态添加路由
【发布时间】:2018-06-04 10:54:53
【问题描述】:

我正在尝试从 json 读取路由并将它们附加到 mux ,但不是附加它似乎覆盖了路由。

代码sn-p

 func main() {

    configLoader()

    dispatchMux := http.NewServeMux()

    for _, site := range ServerConfigData.Sites {
        append(dispatchMux, site.Incomming, site.Forward)
    }

    // Start the server

    color.Green("Server Spinned Up on 2096")
    http.ListenAndServe(":2096", dispatchMux)
}

 // Route Appender
 func append(mux *http.ServeMux, incomming, forward string) {
        color.Yellow("Starting ", incomming, " on ", forward, "\n")
        parsedURL, _ := url.Parse(forward)
        mux.Handle(incomming, httputil.NewSingleHostReverseProxy(parsedURL))
}

【问题讨论】:

  • 您需要对服务器对象有一个全局引用,在您的路由处理程序之一中引用它
  • incoming的值是多少?
  • "incomming":"/a"
  • 不应将函数命名为 append,因为它与 built-in function append 冲突。
  • 不知道原因,但是当我将 append 的代码移入 for 循环时,它的工作原理

标签: go


【解决方案1】:
func main() {

    configLoader()

    dispatchMux := http.NewServeMux()

    for _, site := range ServerConfigData.Sites {

        //Previously code of append function
        parsedURL, _ := url.Parse(site.Forward)
        fmt.Println(site.Incomming)
        dispatchMux.Handle(site.Incomming, httputil.NewSingleHostReverseProxy(parsedURL))

    }    
    // Start the server    
    color.Green("Server Spinned Up on 2096")
    http.ListenAndServe(":80", dispatchMux)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2014-10-09
    • 2014-12-25
    • 2014-03-13
    • 2018-07-27
    相关资源
    最近更新 更多