为了账号安全,请及时绑定邮箱和手机立即绑定

如何同时运行多个 Go lang http 服务器并使用命令行对其进行测试?

如何同时运行多个 Go lang http 服务器并使用命令行对其进行测试?

Go
喵喵时光机 2022-04-20 17:46:26
我的目标是同时运行多个 Go HTTP 服务器。我在使用 Nginx 反向代理时访问在多个端口上运行的 Go HTTP 服务器时遇到了一些问题。最后,这是我用来运行多个服务器的代码。package mainimport (    "net/http"    "fmt"    "log")func main() {    // Show on console the application stated    log.Println("Server started on: http://localhost:9000")    main_server := http.NewServeMux()    //Creating sub-domain    server1 := http.NewServeMux()    server1.HandleFunc("/", server1func)    server2 := http.NewServeMux()    server2.HandleFunc("/", server2func)    //Running First Server    go func() {        log.Println("Server started on: http://localhost:9001")        http.ListenAndServe("localhost:9001", server1)    }()    //Running Second Server    go func() {        log.Println("Server started on: http://localhost:9002")        http.ListenAndServe("localhost:9002", server2)    }()    //Running Main Server    http.ListenAndServe("localhost:9000", main_server)}func server1func(w http.ResponseWriter, r *http.Request) {    fmt.Fprintf(w, "Running First Server")}func server2func(w http.ResponseWriter, r *http.Request) {    fmt.Fprintf(w, "Running Second Server")}我犯的几个新手错误:ping http://localhost:9000 -- 如前所述,ping 用于主机而不是 Web 地址。请改用wget http://localhost:9000。感谢其他人的纠正。在服务器上运行应用程序时结束 SSH 会话——关闭会话后,它也会关闭应用程序。使用 Ctrl + Z - 如果您使用单个终端窗口并且您将使用 Ctrl + Z,它将暂停程序并且您在访问服务器时会遇到问题我希望它能帮助像我这样的新手 Go lang 程序员。
查看完整描述

1 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

经典 ping 不适用于测试 TCP 端口,仅适用于主机(请参阅https://serverfault.com/questions/309357/ping-a-specific-port)。我见过许多框架提供了一个“ping”选项来测试服务器是否还活着,这可能是错误的根源。


我喜欢使用 netcat:


$ nc localhost 8090 -vvv

nc: connectx to localhost port 8090 (tcp) failed: Connection refused


$ nc localhost 8888 -vvv

found 0 associations

found 1 connections:

     1: flags=82<CONNECTED,PREFERRED>

     outif lo0

     src ::1 port 64550

     dst ::1 port 8888

     rank info not available

     TCP aux info available


Connection to localhost port 8888 [tcp/ddi-tcp-1] succeeded!

您可能必须使用sudo yum install netcator安装它sudo apt-get install netcat(分别对于基于 RPM 和 DEB 的发行版)。


查看完整回答
反对 回复 2022-04-20
  • 1 回答
  • 0 关注
  • 452 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号