Add http server initial setup
This commit is contained in:
82
main.go
Normal file
82
main.go
Normal file
@@ -0,0 +1,82 @@
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user