83 lines
1.6 KiB
Go
83 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
const keyServerAddr string = "adm-server"
|
|
|
|
func main() {
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
fmt.Printf("%s: got / request\n", ctx.Value((keyServerAddr)))
|
|
|
|
path := r.URL.Path
|
|
|
|
if path != "/" {
|
|
w.WriteHeader(404)
|
|
io.WriteString(w, "Not found")
|
|
return
|
|
}
|
|
|
|
io.WriteString(w, "This is the index route")
|
|
})
|
|
|
|
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
fmt.Printf("%s: got /test request\n", ctx.Value((keyServerAddr)))
|
|
|
|
io.WriteString(w, "Test")
|
|
})
|
|
|
|
ctx, cancelCtx := context.WithCancel(context.Background())
|
|
|
|
serverOne := &http.Server{
|
|
Addr: ":3000",
|
|
Handler: mux,
|
|
BaseContext: func(l net.Listener) context.Context {
|
|
ctx = context.WithValue(ctx, keyServerAddr, l.Addr().String())
|
|
return ctx
|
|
},
|
|
}
|
|
|
|
serverTwo := &http.Server{
|
|
Addr: ":3001",
|
|
Handler: mux,
|
|
BaseContext: func(l net.Listener) context.Context {
|
|
ctx = context.WithValue(ctx, keyServerAddr, l.Addr().String())
|
|
return ctx
|
|
},
|
|
}
|
|
|
|
go func() {
|
|
err := serverOne.ListenAndServe()
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
fmt.Printf("server one closed\n")
|
|
} else if err != nil {
|
|
fmt.Printf("error listening for server one: %s\n", err)
|
|
}
|
|
cancelCtx()
|
|
}()
|
|
|
|
go func() {
|
|
err := serverTwo.ListenAndServe()
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
fmt.Printf("server two closed\n")
|
|
} else if err != nil {
|
|
fmt.Printf("error listening for server two: %s\n", err)
|
|
}
|
|
cancelCtx()
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
}
|