-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
75 lines (61 loc) · 1.62 KB
/
server.go
File metadata and controls
75 lines (61 loc) · 1.62 KB
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
package gophersinaqueue
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"time"
)
type Job struct {
Name string
Delay int
}
// Job queue length (channel capacity)
const JobQueueLength = 20
// Gophers ofice size (channel capacity)
const GophersOfficeSize = 4
// Jobs queue (channel of jobs)
var JobsQueue = make(chan Job, JobQueueLength)
// Gophers office (channel of whatever)
var GophersOffice = make(chan bool, GophersOfficeSize)
// Very long and complicated process
func process(i int) {
time.Sleep(time.Duration(i) * time.Second)
// Gopher is exhausted and leaves the office
<-GophersOffice
}
func init() {
// Queues management is started in an independent routine
go func() {
// Infinite loop for distributing incoming jobs to idle gophers
for {
// Gopher gets into the office
GophersOffice <- true
go func() {
select {
case job := <-JobsQueue:
process(job.Delay)
}
}()
}
}()
http.HandleFunc("/job/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
// Send a new job to the queue (send button in UI)
case "POST":
var job Job
if jsonString, err := ioutil.ReadAll(r.Body); err == nil {
json.Unmarshal(jsonString, &job)
// The received job is added to the job queue
JobsQueue <- job
// Channel length / Channel capacity in %
w.Write([]byte(strconv.Itoa(int(float64(len(JobsQueue)) / float64(cap(JobsQueue)) * 100.0))))
}
// Get queue state (refresh button in UI)
case "GET":
// Channel length / Channel capacity in %
w.Write([]byte(strconv.Itoa(int(float64(len(JobsQueue)) / float64(cap(JobsQueue)) * 100.0))))
}
}