forked from Loafter/WebTop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TopDispather.go
68 lines (61 loc) · 1.73 KB
/
TopDispather.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
package main
import "net/http"
import "errors"
import "encoding/json"
import "log"
type TopResponse struct {
ProcessItems []ProcessItem
}
type KillResponse struct {
KilResult string
}
type KillRequest struct {
BasicRequest
Pid int `Pid:"Type,string,omitempty"`
}
type TopRequest struct {
BasicRequest
}
type TopDispatcher struct {
top Top
}
func (serviceStateDispatcher *TopDispatcher) Dispatch(request Request, responseWriter http.ResponseWriter, httpRequest *http.Request) error {
switch request.RequestType() {
case TopProcess:
topProcessList, err := serviceStateDispatcher.top.GetProcessList()
if err != nil {
stErr := "error get process list "
log.Println(stErr)
return errors.New("error get process list ")
}
topResponse := TopResponse{ProcessItems: topProcessList}
tr, err := json.Marshal(topResponse)
if err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError)
return err
}
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.Write(tr)
case KillProcess:
killRequest := request.(KillRequest)
err := serviceStateDispatcher.top.KillProcess(killRequest.Pid)
var killResultMsg string
if err != nil {
killResultMsg = err.Error()
} else {
killResultMsg = "Send kill top process" + string(killRequest.Pid)
}
killResponseResponse := KillResponse{KilResult: killResultMsg}
tr, err := json.Marshal(killResponseResponse)
if err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError)
return err
}
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.Write(tr)
}
return nil
}
func (serviceStateDispatcher *TopDispatcher) StartMeasure() {
serviceStateDispatcher.top.StartCollectInfo()
}