-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
84 lines (67 loc) · 1.45 KB
/
backend.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
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"sync"
)
type respHandler struct {
mu sync.Mutex
n uint64
}
var (
urls = [...]string{
"https://www.google.com/teapot",
"https://example.com",
}
overflowMsg string
)
func getStatus(wg *sync.WaitGroup, url string, ch chan string) (err error) {
defer wg.Done()
resp, err := http.Get(url)
if err != nil {
log.Println("Error:", err)
return err
} else {
log.Println("Proxy: GET", url)
}
defer resp.Body.Close()
ch <- resp.Status
return nil
}
func (h *respHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
ch := make(chan string, len(urls))
h.mu.Lock()
if h.n == ^uint64(0) {
overflowMsg = "more than" + " "
} else {
h.n++
}
h.mu.Unlock()
fmt.Fprintf(w, "Backend: %s%d requests served.\n", overflowMsg, h.n)
for _, url := range urls {
wg.Add(1)
go getStatus(&wg, url, ch)
}
wg.Wait()
close(ch)
for m := range ch {
fmt.Fprintf(w, "Backend: external service responds: %q\n", m)
}
}
func DumpReq(w http.ResponseWriter, r *http.Request) {
resp, err := httputil.DumpRequest(r, true)
if err != nil {
log.Printf("DumpReq error: %s\n", err)
}
fmt.Fprintf(w, "Backend: header dump is:\n%s", resp)
}
func main() {
const port string = "8080"
log.Printf("Starting the backend service on port %s.\n", port)
http.Handle("/", new(respHandler))
http.HandleFunc("/dumpreq", DumpReq)
log.Fatal(http.ListenAndServe(":"+port, nil))
}