/
13_fast_request.go
65 lines (57 loc) · 1.21 KB
/
13_fast_request.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
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
const port = ":8000"
func main() {
for i := 0; i < 100; i++ {
go func() {
// req := http.Request{}
resp, err := http.Get("http://localhost" + port)
if err != nil {
fmt.Println("err1:", err)
return
} else {
fmt.Println("success")
}
// b, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// fmt.Println("err2:", err)
// return
// }
// fmt.Println(string(b))
_, err = io.Copy(ioutil.Discard, resp.Body)
if err != nil {
fmt.Println("err2:", err)
return
}
}()
}
mainRouter := http.NewServeMux()
mainRouter.HandleFunc("/", handler)
log.Println("Serving http://localhost" + port)
if err := http.ListenAndServe(port, mainRouter); err != nil {
panic(err)
}
}
var cnt int
var used = make(map[string]struct{})
func handler(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case "GET":
if _, ok := used[req.RemoteAddr]; !ok {
used[req.RemoteAddr] = struct{}{}
} else {
fmt.Println("duplicate:", req.RemoteAddr)
}
fmt.Println("hello", cnt, req.RemoteAddr)
fmt.Fprintln(w, "Hello World!", cnt)
cnt++
default:
http.Error(w, "Method Not Allowed", 405)
}
}