Reputation: 387
EDIT: My aim was to run multiple Go HTTP Servers at the same time. I was facing some issues while accessing the Go HTTP server running on multiple ports while using Nginx reverse proxy.
Finally, this is the code that I used to run multiple servers.
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")
}
Few newbie mistakes I was making:
I hope it will help newbie Go lang programmers like me.
Upvotes: 5
Views: 11656
Reputation: 77241
The classic ping does not work for testing TCP ports, just hosts (see https://serverfault.com/questions/309357/ping-a-specific-port). I've seen many frameworks provide a "ping" option to test if the server is alive, may be this is the source of the mistake.
I like to use 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!
You may have to install it with sudo yum install netcat
or sudo apt-get install netcat
(respectively for RPM and DEB based distros).
Upvotes: 5