dq13733519262 2014-01-17 10:12 采纳率: 0%
浏览 198
已采纳

在一个go程序中同时运行两个Web服务器

In a go program, I want to run two web servers at the same time,
obviously they will be serving on two different ports (and ip addresses if necessary),
the problem is with the call to http.handle, when I try to register handler for '/' for the second server, it panics and says there is already a handler associated with '/',
I guess I need to create a mux in addition to the DefaultServeMux and I tried to do it using the gorillaMux but couldn't figure it out,

Is there something fundamentally wrong with running two web servers in the same program/process.

To make it more clear, one of the two web servers is a being used as a regular web server, I need the second one to act as an RPC server to communicate stuff between instances of the program running on different nodes of a cluster,

EDIT: to make it a bit more clear, this is not the actual code but it is the gist

myMux := http.NewServeMux()
myMux.HandleFunc("/heartbeat", heartBeatHandler)

http.Handle("/", myMux)

server := &http.Server{
    Addr:    ":3400",
    Handler: myMux,
}
go server.ListenAndServe()

gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", indexHandler)
gorillaMux.HandleFunc("/book", bookHandler)

http.Handle("/", gorillaMux)

server := &http.Server{
    Addr:    ":1234",
    Handler: gorillaMux,
}

log.Fatal(server.ListenAndServe())
  • 写回答

1条回答 默认 最新

  • dowm41315 2014-01-17 11:09
    关注

    I think you just need remove these lines:

    http.Handle("/", myMux)
    http.Handle("/", gorillaMux)
    

    All routes are already defined in myMux and gorillaMux.

    Check this: http://play.golang.org/p/wqn4CZ01Z6

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效