Created
February 11, 2021 19:28
-
-
Save refs/0453abf093b373703f5d7b27038eecc6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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