-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.go
115 lines (99 loc) · 2.5 KB
/
server.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
// Stefan Nilsson 2013-03-17
// This program runs three independent servers at
//
// http://localhost:8080, http://localhost:8081, and http://localhost:8082.
//
// Each server accepts HTTP Get requests and answers with an integer
// indicating the current (fake) temperature at KTH in Stockholm.
//
// The servers are unreliable. The response time varies from a few seconds
// up to an hour. When the service is down, which happens quite frequently,
// you get HTTP Error 503 - Service unavailable.
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"sync"
"time"
)
func init() {
log.SetPrefix("Weather: ")
}
// Server
func main() {
Station = NewWeatherStation("KTH")
for _, port := range []string{":8080", ":8081", ":8082"} {
s := &http.Server{
Addr: port,
Handler: http.HandlerFunc(ServeTemperature),
}
go func() {
log.Printf("starting server at localhost%s", s.Addr)
err := s.ListenAndServe()
if err != nil {
log.Fatalf("ListenAndServe: %v", err)
}
}()
}
select {} // Block forever.
}
func ServeTemperature(w http.ResponseWriter, r *http.Request) {
switch x := rand.Float32(); true {
case x < 0.70:
time.Sleep(time.Duration(rand.Intn(1200)) * time.Millisecond)
fmt.Fprintln(w, Station.CurrentTemp())
case x < 0.85:
time.Sleep(time.Hour)
default:
http.Error(w, "Service unavailable", http.StatusServiceUnavailable)
}
}
// Weather station
var Station *WeatherStation
type WeatherStation struct {
mutex sync.RWMutex
name string
temp int
}
func NewWeatherStation(name string) *WeatherStation {
station := &WeatherStation{name: name}
station.TakeMeasurement()
go func() {
for {
time.Sleep(time.Minute)
station.TakeMeasurement()
}
}()
return station
}
func (w *WeatherStation) CurrentTemp() int {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.temp
}
func (w *WeatherStation) TakeMeasurement() {
w.mutex.Lock()
defer w.mutex.Unlock()
w.temp = fake.currentTemp() // Fake it for now.
log.Printf("%d˚C at %s\n", w.temp, w.name)
}
// Fake temperature model for Stockholm
var fake fakeTempModel
type fakeTempModel struct {
temp int
monthlyAverage int
firstTemp sync.Once
}
func (f *fakeTempModel) currentTemp() int {
f.firstTemp.Do(func() {
now := time.Now()
Stockholm := []int{-3, -3, 0, 5, 11, 16, 17, 16, 12, 8, 3, -1}
f.monthlyAverage = Stockholm[now.Month()-1]
rand.Seed(now.UnixNano())
f.temp = f.monthlyAverage - 4 + rand.Intn(8)
})
f.temp += int(rand.NormFloat64() - 0.02*float64(f.temp-f.monthlyAverage))
return f.temp
}