-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
128 lines (114 loc) · 3.12 KB
/
server.go
File metadata and controls
128 lines (114 loc) · 3.12 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"encoding/json"
"fmt"
"math"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"time"
)
type Weather struct {
Temperature float64
Conditions string
}
var start = time.Now()
var lastRequests = struct {
sync.RWMutex
m map[string]time.Time
}{m: make(map[string]time.Time)}
var conditions = [...]string{"cloudy", "sunny", "foggy"}
func getUserIp(req *http.Request) string {
//normalize for running locally or on heroku
forwardedIp := req.Header.Get("X-Forwarded-For")
if forwardedIp == "" {
parts := strings.SplitN(req.RemoteAddr, ":", 2)
if len(parts) > 0 {
return parts[0]
}
return req.RemoteAddr
} else {
return forwardedIp
}
}
func calculateTemp() float64 {
//Sin wave of temperatures
return math.Ceil(math.Sin(time.Since(start).Seconds()/300) * 100)
}
func getWeather() Weather {
return Weather{calculateTemp(), conditions[rand.Intn(3)]}
}
func generateRes(res http.ResponseWriter) {
// Randomly give back a good response or random garbage :)
dice := rand.Intn(20)
switch dice {
default:
res.Header().Set("Content-Type", "application/json")
response, _ := json.Marshal(getWeather())
fmt.Fprintln(res, string(response))
case 1:
res.Header().Set("Content-Type", "application/json")
fmt.Fprintln(res, "{ weather: ++_--_(*&^$#$^&*(")
case 2:
res.WriteHeader(http.StatusTeapot)
fmt.Fprintln(res, "I'm A Teapot!")
case 3:
res.Header().Set("Content-Type", "application/json")
fmt.Fprintln(res, "{\"Server Tired\": \"ZzZzZzZzZzZzZzZzZ\" }")
case 4:
res.Header().Set("Content-Type", "application/json")
fmt.Fprintln(res, "{\"Temperature\": \"<script>window.location = 'http://www.google.com'</script>\", \"Conditions\":\"<script>window.location = 'http://www.google.com'</script>\" }")
case 5:
res.Header().Set("Content-Type", "application/json")
response, _ := json.Marshal(getWeather())
time.Sleep(300 * time.Second)
fmt.Fprintln(res, string(response))
}
}
func getTemp(res http.ResponseWriter, req *http.Request) {
//Allows cross-domain requests in modern browsers
res.Header().Set("Access-Control-Allow-Origin", "*")
ip := getUserIp(req)
//Reject if this IP has made a request in the last second
lastRequests.RLock()
lr, ok := lastRequests.m[ip]
lastRequests.RUnlock()
maxRate := time.Duration(1)
if !ok || time.Since(lr) > maxRate*time.Second {
lastRequests.Lock()
lastRequests.m[ip] = time.Now()
lastRequests.Unlock()
generateRes(res)
} else {
// Add a 3 second penalty
penalty := time.Duration(3)
lastRequests.Lock()
lastRequests.m[ip] = time.Now().Add(penalty * time.Second)
lastRequests.Unlock()
if rand.Intn(4) > 1 {
res.WriteHeader(429)
fmt.Fprintf(res, "Exceeded one request every %d seconds. Now you have to wait %d seconds!\n", maxRate, penalty+maxRate)
} else {
// Thanks, Twitter.
res.WriteHeader(420)
fmt.Fprintln(res, "Enhance your calm")
}
}
}
func main() {
rand.Seed(time.Now().Unix())
http.HandleFunc("/", getTemp)
fmt.Println("listening...")
port := ""
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
} else {
port = "5000"
}
err := http.ListenAndServe(":"+port, nil)
if err != nil {
panic(err)
}
}