Skip to content

Instantly share code, notes, and snippets.

@filewalkwithme
Last active February 16, 2024 23:22
Show Gist options
  • Save filewalkwithme/24363472e7424bbe7028 to your computer and use it in GitHub Desktop.
Save filewalkwithme/24363472e7424bbe7028 to your computer and use it in GitHub Desktop.
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 "))
}
@neontorrent
Copy link

@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