-
Notifications
You must be signed in to change notification settings - Fork 0
/
goAPIAnalyzer.go
338 lines (271 loc) · 7.62 KB
/
goAPIAnalyzer.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package main
import (
"fmt"
"github.com/pborman/getopt/v2"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"sort"
"strconv"
"time"
)
/**
Struct contains the required values for each request entity.
*/
type responseEntity struct {
time time.Duration
responseCode int
responseSize int
}
/**
Function to get server Response
Returns a server response and start time.
*/
func getServerResponse(url string) (*http.Response, time.Time) {
spaceClient := http.Client{
Timeout: time.Second * 2,
}
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
request.Header.Set("User-Agent", "spacecount-tutorial")
start := time.Now()
response, getErr := spaceClient.Do(request)
if getErr != nil {
log.Fatal(getErr)
}
return response, start
}
/**
Function to get total request time and response size.
Returns request time and response size.
*/
func performTimedUtils(response *http.Response, startTime time.Time) (time.Duration, bool, int) {
requestTime := time.Since(startTime)
if response.Body != nil {
requestTime := time.Since(startTime)
dump, err := httputil.DumpResponse(response, true)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
return requestTime, true, len(dump)
}
return requestTime, false, 0
}
/**
Function to print response from single url.
*/
func printBody(response *http.Response) {
body, readErr := ioutil.ReadAll(response.Body)
if readErr != nil {
log.Fatal(readErr)
}
bodyString := string(body)
fmt.Println("Response Body: ", bodyString)
}
/**
Function to get command line arguments.
Returns url and number of request.
*/
func runNumberedRequests() (string, int) {
urlStr := getopt.StringLong("url", 'u',
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=IBM&apikey=demo",
" The url to fetch! ")
profileStr := getopt.StringLong("profile", 'p', "0",
" Number of fetches required. \n Default url"+
"is https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=IBM&apikey=demo " +
"if not explicitly set with --url flag")
optHelp := getopt.BoolLong("help", 0, "Help")
getopt.Parse()
if *optHelp {
getopt.Usage()
os.Exit(0)
}
requestsNo, err := strconv.ParseInt(*profileStr, 10, 64)
if err != nil {
log.Fatal("Invalid request number : Err : ", err)
}
return *urlStr, int(requestsNo)
}
/**
Function to return minimum and maximum response time .
Returns minimum and maximum response time.
*/
func minMaxTime(sliceProcess []time.Duration) (time.Duration, time.Duration) {
var max = sliceProcess[0]
var min = sliceProcess[0]
for _, value := range sliceProcess {
if max < value {
max = value
}
if min > value {
min = value
}
}
return min, max
}
/**
Function to return minimum and maximum buffer size.
Returns minimum and maximum buffer responses.
*/
func minMaxBufferSize(sliceProcess []int) (int, int) {
var max = sliceProcess[0]
var min = sliceProcess[0]
for _, value := range sliceProcess {
if max < value {
max = value
}
if min > value {
min = value
}
}
return min, max
}
/**
Function to calculate median time.
Returns median time.
*/
func medianTime(sliceProcess []time.Duration) time.Duration {
if len(sliceProcess) == 1 {
return sliceProcess[0]
}
floatTimeArray := []float64{}
for _, timeSingle := range sliceProcess {
floatTimeArray = append(floatTimeArray, float64(timeSingle))
}
sort.Float64s(floatTimeArray)
midEle := len(floatTimeArray) / 2.0
if midEle%2 == 0 {
return time.Duration((floatTimeArray[midEle-1] + floatTimeArray[midEle]) / 2)
}
return time.Duration(floatTimeArray[midEle])
}
/**
Function to calculate mean time.
Returns the mean time.
*/
func meanTime(sliceProcess []time.Duration) time.Duration {
total := 0.0
for _, timeSingle := range sliceProcess {
total += float64(timeSingle)
}
return time.Duration(total / float64(len(sliceProcess)))
}
/**
Function to calculate success percentage of requests.
Returns the success percentage.
*/
func percentSuccess(sliceProcess []int) float64 {
totalUnsuccessfull := 0
totalReqs := len(sliceProcess)
for _, code := range sliceProcess {
if code == 200 {
totalUnsuccessfull++
}
}
return float64(totalUnsuccessfull/totalReqs) * 100
}
/**
Function to remove duplicate error codes.
Returns an array without duplicate error codes.
*/
func getUniqueErrorCodes(sliceProcess []int) []int {
keys := make(map[int]bool)
var uniqueErrorCodes []int
for _, code := range sliceProcess {
if _, value := keys[code]; !value {
keys[code] = true
uniqueErrorCodes = append(uniqueErrorCodes, code)
}
}
return uniqueErrorCodes
}
/**
Function to generate a list of error codes
Returns error code list with duplicates.
*/
func getErrorCodes(sliceProcess []int) []int {
var errorCodesSlice []int
for _, code := range sliceProcess {
if code != 200 {
errorCodesSlice = append(errorCodesSlice, code)
}
}
return errorCodesSlice
}
/**
Function to format final answer
*/
func formatPrintProfiler(numOfReq int, fastestTime time.Duration, slowestTime time.Duration,
meanTm time.Duration, medianTm time.Duration, percenRequestSuccess float64,
uniqueErrorCodeSlice []int, minResponseSize int, maxResponseSize int) {
fmt.Println("\n Number Of Requests: ", numOfReq)
fmt.Println(" Fastest Time: ", fastestTime, "\n Slowest Time: ", slowestTime,
"\n Mean Time: ", meanTm, "\n Median Time: ", medianTm, "\n Percent Success Requests: ",
percenRequestSuccess)
if len(uniqueErrorCodeSlice) == 0 {
fmt.Println("Unique Error Code List is empty i.e only 200 response code encountered ",
uniqueErrorCodeSlice)
} else {
fmt.Println("Unique Error Code List: ", uniqueErrorCodeSlice)
}
fmt.Println("Smallest Response Size in bytes: ", minResponseSize,
"\n Largest Response Size in bytes: ", maxResponseSize)
}
/**
Function to get appropriate calculations for the final response.
*/
func processProfilerData(responseArray []responseEntity) {
numOfReq := len(responseArray)
var timingArray []time.Duration
var responseCodes []int
var responseSizes []int
for _, individualResponse := range responseArray {
timingArray = append(timingArray, individualResponse.time)
responseCodes = append(responseCodes, individualResponse.responseCode)
responseSizes = append(responseSizes, individualResponse.responseSize)
}
slowestTime, fastestTime := minMaxTime(timingArray)
meanTm := meanTime(timingArray)
medianTm := medianTime(timingArray)
percenRequestSuccess := percentSuccess(responseCodes)
errorCodeSlice := getErrorCodes(responseCodes)
uniqueErrorCodeSlice := getUniqueErrorCodes(errorCodeSlice)
minResponseSize, maxResponseSize := minMaxBufferSize(responseSizes)
formatPrintProfiler(numOfReq, fastestTime, slowestTime, meanTm,
medianTm, percenRequestSuccess, uniqueErrorCodeSlice,
minResponseSize, maxResponseSize)
}
/**
Function to generate a response array containing each request element.
*/
func responseProfiler(numOfRequests int, url string) {
var responseArray []responseEntity
for i := 0; i < numOfRequests; i++ {
response, startTime := getServerResponse(url)
requestTime, flagUpdate, responseSz := performTimedUtils(response, startTime)
if flagUpdate == true {
entity := responseEntity{time: requestTime, responseCode: response.StatusCode, responseSize: responseSz}
responseArray = append(responseArray, entity)
}
}
processProfilerData(responseArray)
}
/**
Main Code Controller
*/
func main() {
url, reqNo := runNumberedRequests()
if reqNo == 0 {
fmt.Println("URL: ", url, " \n Number Of Request: ", reqNo+1)
response, _ := getServerResponse(url)
printBody(response)
} else {
fmt.Println("URL: ", url)
responseProfiler(reqNo, url)
}
}