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

Adi*_*Adi 5 linux ubuntu go

编辑:我的目标是同时运行多个 Go HTTP 服务器。我在使用 Nginx 反向代理访问在多个端口上运行的 Go HTTP 服务器时遇到了一些问题。

最后,这是我用来运行多个服务器的代码。

package main

import (
    "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")
}
Run Code Online (Sandbox Code Playgroud)

我犯过的一些新手错误:

  1. ping http://localhost:9000 —— 如前所述,ping 用于主机而不是网址。请改用wget http://localhost:9000。感谢其他人的纠正。
  2. 在服务器上运行应用程序时结束 SSH 会话- 一旦关闭会话,它也将关闭应用程序。
  3. 使用 Ctrl + Z - 如果您使用单个终端窗口并且将使用 Ctrl + Z,它将暂停程序,并且您在访问服务器时将遇到问题

我希望它能帮助像我这样的 Go 语言新手。

Pau*_*ine 5

经典 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!
Run Code Online (Sandbox Code Playgroud)

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