Skip to content

Instantly share code, notes, and snippets.

@filewalkwithme
Created February 7, 2015 21:50
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save filewalkwithme/0199060b2cb5bbc478c5 to your computer and use it in GitHub Desktop.
Save filewalkwithme/0199060b2cb5bbc478c5 to your computer and use it in GitHub Desktop.
Listening multiple ports on golang http servers
package main
import (
"net/http"
)
func main() {
finish := make(chan bool)
server8001 := http.NewServeMux()
server8001.HandleFunc("/foo", foo8001)
server8001.HandleFunc("/bar", bar8001)
server8002 := http.NewServeMux()
server8002.HandleFunc("/foo", foo8002)
server8002.HandleFunc("/bar", bar8002)
go func() {
http.ListenAndServe(":8001", server8001)
}()
go func() {
http.ListenAndServe(":8002", server8002)
}()
<-finish
}
func foo8001(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8001: foo "))
}
func bar8001(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8001: bar "))
}
func foo8002(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8002: foo "))
}
func bar8002(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8002: bar "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment