Listening on Multiple HTTP Sockets

Jun 17, 2015 Golang

Introduction

There are times when you need to have two listeners, unfortunately, they will both block. This will usually result in the first http listener to server correctly, and the second one never gets called.

In order to get around this, we can use the WaitGroup library, which handles some locking around lower level functions in Go.

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

Golang documentation on sync.WaitGroups

Code Example

The below has been documented to provide some guidance into what is going on.

package main

import (
  "sync"
  "log"
  "net/http"
)

// Create a waitgroup, which is Golang for Magic.
// We are using a WaitGroup to block main() until
// all the listeners return
func main() {

  // Create a waitgroup that will handle
  wg := sync.WaitGroup{}

  // Add a counter to the waitgroup and then run the
  // http server in a goroutine
  wg.Add(1)
  go func() {
    log.Println("--> Starting First server on port: 8080")
    panic(http.ListenAndServe(":8080", http.FileServer(http.Dir("."))))
    wg.Done()
  }()


  // Add another counter to the waitgroup and then run
  // the http server in a goroutine
  wg.Add(1)
  go func() {
    log.Println("--> Starting Second server on port: 9090")
    panic(http.ListenAndServe(":9090", http.FileServer(http.Dir("."))))
    wg.Done()
  }()

  wg.Wait()
}

comments powered by Disqus