Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Listening multiple ports on golang http servers (using http.Handler)
package main
import (
"net/http"
)
func main() {
go func() {
http.ListenAndServe(":8001", &fooHandler{})
}()
//the last call is outside goroutine to avoid that program just exit
http.ListenAndServe(":8002", &barHandler{})
}
type fooHandler struct {
}
func (m *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8001: foo "))
}
type barHandler struct {
}
func (m *barHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8002: bar "))
}
@eklitzke

This comment has been minimized.

Copy link

eklitzke commented Sep 7, 2016

you are a hero

@brtn

This comment has been minimized.

Copy link

brtn commented Sep 25, 2016

Why not just use go http.ListenAndServe(":8001", &fooHandler{}) ?

@rillig

This comment has been minimized.

Copy link

rillig commented Mar 5, 2017

With the necessary error handling, the code should look like this:

go func() {
    log.Fatal(http.ListenAndServe(":8080", server))
}()
log.Fatal(http.ListenAndServeTLS(":8443", "server.crt", "server.key", server))
@texasbruce

This comment has been minimized.

Copy link

texasbruce commented Jun 19, 2018

@brtn because it allows you to pass data into the handler

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.