-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
198 lines (156 loc) · 4.54 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// YAPC start point.
package main
import (
"fmt"
"log"
"net"
"net/http"
"time"
"os"
"os/signal"
"syscall"
"sync"
"io/ioutil"
)
type CacheMemory struct {
sync.RWMutex
objectList map[string][]byte
}
var (
cacheMemory = CacheMemory {
objectList: make(map[string][]byte),
}
)
const listenAddr = ":8098"
// Main function. Start http handlers.
func main() {
fmt.Println("Starting YAPC server!")
handleSignals()
http.HandleFunc("/", handler)
err := http.ListenAndServe(listenAddr, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Finishing YAPC server!")
}
// Handle all signals to the process.
func handleSignals() {
signalChannel := make(chan os.Signal, 1)
signal.Notify(signalChannel,
syscall.SIGINT,
syscall.SIGHUP,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGABRT,
)
go func() {
for {
signal := <- signalChannel
fmt.Println()
fmt.Println(signal)
switch signal {
case syscall.SIGINT:
// Handle SIGINT
os.Exit(0)
case syscall.SIGHUP:
// Handle SIGHUP
case syscall.SIGTERM:
// Handle SIGTERM
case syscall.SIGQUIT:
// Handle SIGQUIT
case syscall.SIGABRT:
// Handle SIGABRT
}
}
}()
}
// Main handler. Receive a request and proxy them to the upstream.
func handler(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
hashKey := CreateHash(r.URL.String())
// Verify if is a cache hit.
isHit, statusCode, responseLength, err := verifyIsHit(hashKey, w)
if err != nil {
log.Fatal(err)
}
if isHit == false {
// If is a miss, proxy to the upstream.
statusCode, responseLength, err = proxyUpstreamRequest(w, r, hashKey)
if err != nil {
log.Fatal(err)
}
}
elapsedTime := time.Since(startTime)
logRequest(r, statusCode, responseLength, elapsedTime, isHit)
}
func verifyIsHit(hashKey string, w http.ResponseWriter) (exist bool, statusCode int, upstreamResponseLength int, err error) {
cacheMemory.RLock()
body, exist := cacheMemory.objectList[hashKey]
cacheMemory.RUnlock()
if !exist {
return
}
// Set Yapc-Cache-State header.
w.Header().Set("Yapc-Cache-State", "hit")
// Using io.Write to dump the data object to the downstream.
_, err = w.Write(body)
if err != nil {
return
}
statusCode = http.StatusOK
upstreamResponseLength = len(body)
return
}
// Proxy a request to the Upstream.
func proxyUpstreamRequest(w http.ResponseWriter, r *http.Request, hashKey string) (statusCode int, upstreamResponseLength int, err error) {
upstreamResponse, err := http.Get(r.URL.String())
if err != nil {
return
}
defer upstreamResponse.Body.Close()
// Set Yapc-Cache-State header.
w.Header().Set("Yapc-Cache-State", "fetch")
// Assumption: read the whole object and then send to downstream is a good approach only for small objects.
// Probably, in another version, the objects will be read in chunks (maybe 4KB).
body, err := ioutil.ReadAll(upstreamResponse.Body)
cacheMemory.Lock()
cacheMemory.objectList[hashKey] = body
cacheMemory.Unlock()
_, err = w.Write(body)
if err != nil {
return
}
statusCode = upstreamResponse.StatusCode
upstreamResponseLength = len(body)
return
}
// Get IP from a http request.
func getIP(r *http.Request) string {
if ipProxy := r.Header.Get("X-Forwarded-For"); len(ipProxy) > 0 {
return ipProxy
}
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}
// Log a http request.
func logRequest(r *http.Request, upstreamStatusCode int, upstreamResponseLength int, elapsedUpstreamGetTime time.Duration, isHit bool) {
// Log format: [Timestamp] RemoteAddr "URL" Status BytesSent "HttpUserAgent" UpstreamResponseTime
// Example : [2006-01-02T15:04:05Z07:00] 87.19.231.27 "http://www.teste.com.br/xyz" 200 12345 "CURL" 123
var cacheState string
if isHit {
cacheState = "HIT"
} else {
cacheState = "MISS"
}
log.Printf(
"[%s] %s %s %q %d %d %q %v",
time.Now().Format(time.RFC3339),
getIP(r),
cacheState,
r.URL.String(),
upstreamStatusCode,
upstreamResponseLength,
r.UserAgent(),
elapsedUpstreamGetTime,
)
}