Skip to content

Instantly share code, notes, and snippets.

@refs
Created February 11, 2021 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save refs/0453abf093b373703f5d7b27038eecc6 to your computer and use it in GitHub Desktop.
Save refs/0453abf093b373703f5d7b27038eecc6 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
)
func main() {
block := make(chan os.Signal, 2)
signal.Notify(block, os.Interrupt)
server1 := newHTTPServer("server_1", ":9200")
server2 := newHTTPServer("server_2", ":9201")
go run(&server1)
go run(&server2)
<-block
server1.Shutdown(context.Background())
<-block
server2.Shutdown(context.Background())
close(block)
return
}
func newHTTPServer(name string, addr string) http.Server {
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("hello, server %v", name)))
}))
return http.Server{
Addr: addr,
Handler: mux,
}
}
func run(s *http.Server) {
log.Printf("starting server listening on %v\n", s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Print(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment