-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
115 lines (98 loc) · 2.47 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
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"html"
"net/http"
"strconv"
"time"
)
type ControlMessage struct {
Text string
Number uint64
}
func main() {
// Create controlChannel and statusPollChannel
controlChannel := make(chan ControlMessage)
workerCompleteChan := make(chan bool)
statusPollChannel := make(chan chan bool)
// Initialize workerActive state
workerActive := false
// Start the admin handler
go admin(controlChannel, statusPollChannel)
// Specify the server address
serverAddr := ":3010"
serverURL := "http://localhost" + serverAddr
// Standart Output the server start message
fmt.Printf("Server is started at %s\n", serverURL)
// Start the server
go func() {
err := http.ListenAndServe(serverAddr, nil)
if err != nil {
fmt.Printf("Server error: %v\n", err)
}
}()
for {
select {
// Receive response from statusPollChannel
case respChan := <-statusPollChannel:
respChan <- workerActive
// Process messages from controlChannel
case msg := <-controlChannel:
workerActive = true
go worker(msg, workerCompleteChan)
// Receive worker completion status
case status := <-workerCompleteChan:
workerActive = status
}
}
}
func admin(cc chan ControlMessage, statusPollChannel chan chan bool) {
// /admin handler
http.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
// Parse request form
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get parameters and send control message
number, err := strconv.ParseUint(r.FormValue("number"), 10, 32)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
text := r.FormValue("text")
msg := ControlMessage{
Text: text,
Number: number,
}
cc <- msg
// Create response
fmt.Fprintf(w,"Sent Control message about Text: %s, Number: %d",
html.EscapeString(r.FormValue("text")),
number,
)
})
// /status handler
http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
// Send status poll request
reqChan := make(chan bool)
statusPollChannel <- reqChan
timeout := time.After(time.Second)
select {
case result := <-reqChan:
if result {
fmt.Fprintf(w, "ACTIVE")
} else {
fmt.Fprintf(w, "INACTIVE")
}
case <-timeout:
fmt.Fprintf(w, "TIMEOUT")
}
})
}
// Worker processing
func worker(msg ControlMessage, cc chan bool) {
fmt.Printf("Accepted Control message, Text: %s, Number: %d \n", msg.Text, msg.Number)
cc <- false
}