-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (81 loc) · 2.07 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
)
const keyServerAddr = "serverAddr"
func getRoot(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
hasFirst := r.URL.Query().Has("first")
first := r.URL.Query().Get("first")
hasSecond := r.URL.Query().Has("second")
second := r.URL.Query().Get("second")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("could not read body: %s\n", err)
}
fmt.Printf("%s: got / request. first(%t)=%s, second(%t)=%s, body:\n%s\n",
ctx.Value(keyServerAddr),
hasFirst, first,
hasSecond, second,
body)
io.WriteString(w, "This is my website\n")
}
func getHello(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
fmt.Printf("%s: got /hello requests\n", ctx.Value(keyServerAddr))
myName := r.PostFormValue("myName")
if myName == "" {
w.Header().Set("x-missing-field", "myName")
w.WriteHeader(http.StatusBadRequest)
return
}
io.WriteString(w, fmt.Sprintf("Hello, %s!\n", myName))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", getRoot)
mux.HandleFunc("/hello", getHello)
ctx, cancelCtx := context.WithCancel(context.Background())
serverOne := &http.Server{
Addr: ":8080",
Handler: mux,
BaseContext: func(l net.Listener) context.Context {
ctx = context.WithValue(ctx, keyServerAddr, l.Addr().String())
return ctx
},
}
serverTwo := &http.Server{
Addr: ":1717",
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()
}