编辑:我的目标是同时运行多个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")
}
我做的新手错误很少:
我希望它能帮助像我这样的新手Go lang程序员。
答案 0 :(得分:3)
经典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 netcat
或sudo apt-get install netcat
(分别用于基于RPM和DEB的发行版)进行安装。