Skip to content
Advertisement

How to run multiple Go lang http Servers at the same time and test them using command line?

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:

  1. ping http://localhost:9000 — As mentioned, ping is used for host not a web address. Use wget http://localhost:9000 instead. Thanks for others for correcting it.
  2. Ending SSH session while running the application on server — Once you close your session, it will also shut down the application.
  3. Use of Ctrl + Z — If you are using single terminal window and you will use Ctrl + Z, it will pause the program and you will face issues while accessing the servers

I hope it will help newbie Go lang programmers like me.

Advertisement

Answer

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).

Advertisement