forked from mehrdadrad/mylg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trace.go
91 lines (71 loc) · 1.64 KB
/
trace.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
package httpd
import (
"fmt"
"math/rand"
"net/http"
"strconv"
"github.com/mehrdadrad/mylg/cli"
"github.com/mehrdadrad/mylg/icmp"
)
// initTrace returns an id and creates a gorouting
func initTrace(w http.ResponseWriter, r *http.Request, cfg *cli.Config) {
r.ParseForm()
args := r.FormValue("a")
id := rand.Intn(1000)
ttracker[id] = TTracker{ch: make(chan string, 1)}
t, err := icmp.NewTrace(args, *cfg)
if err != nil {
fmt.Fprintf(w, `{"id": %d, "err": "%s"}`, -1, err.Error())
return
}
go func() {
defer func() {
recover()
}()
resp, _ := t.MRun()
defer close(resp)
for {
select {
case r, _ := <-resp:
ttracker[id].ch <- r.Marshal()
}
}
}()
fmt.Fprintf(w, `{"id": %d, "err": ""}`, id)
}
func getTrace(w http.ResponseWriter, r *http.Request) {
var errMsg = "trace channel is not exist"
r.ParseForm()
id := r.FormValue("id")
i, err := strconv.Atoi(id)
if err != nil {
fmt.Fprintf(w, `{"id": %d, "err": "%s"}`, i, err.Error())
return
}
if _, ok := ttracker[i]; !ok {
fmt.Fprintf(w, `{"id": %d, "err": "%s"}`, i, errMsg)
return
}
if v, ok := <-ttracker[i].ch; ok {
fmt.Fprint(w, v)
} else {
fmt.Fprintf(w, `{"id": %d, "err": "%s"}`, i, errMsg)
}
}
func closeTrace(w http.ResponseWriter, r *http.Request) {
var errMsg = "trace channel is not exist"
r.ParseForm()
id := r.FormValue("id")
i, err := strconv.Atoi(id)
if err != nil {
fmt.Fprintf(w, `{"id": %d, "err": "%s"}`, i, err.Error())
return
}
if _, ok := ttracker[i]; !ok {
fmt.Fprintf(w, `{"id": %d, "err": "%s"}`, i, errMsg)
return
}
close(ttracker[i].ch)
delete(ttracker, i)
fmt.Fprintf(w, `{"id": %d, "err": ""}`, i)
}