编辑:我的目标是同时运行多个 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)
我犯过的一些新手错误:
我希望它能帮助像我这样的 Go 语言新手。
经典 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 netcat或sudo apt-get install netcat(分别针对基于 RPM 和 DEB 的发行版)来安装它。
| 归档时间: |
|
| 查看次数: |
10740 次 |
| 最近记录: |