-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
207 lines (170 loc) · 5.33 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
199
200
201
202
203
204
205
206
207
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/fatih/color"
)
type LoadTestConfig struct {
URL string
NumRequests int
Method string
Data []byte
}
type LoadTestResult struct {
TotalRequests int
SuccessfulRequests int
FailedRequests int
Duration time.Duration
}
func makeRequest(url string, method string, data []byte, requestNum int, wg *sync.WaitGroup, mu *sync.Mutex, result *LoadTestResult) {
defer wg.Done()
startTime := time.Now()
resp, err := http.NewRequest(method, url, nil)
if err != nil {
mu.Lock()
result.FailedRequests++
mu.Unlock()
fmt.Printf(color.RedString("Request %d failed: %v\n"), requestNum, err)
return
}
if data != nil {
resp.Body = http.NoBody
resp.ContentLength = 0
resp.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(data)), nil
}
}
client := http.Client{}
response, err := client.Do(resp)
elapsed := time.Since(startTime)
if err != nil {
mu.Lock()
result.FailedRequests++
mu.Unlock()
fmt.Printf(color.RedString("Request %d failed: %v\n"), requestNum, err)
return
}
defer response.Body.Close()
mu.Lock()
result.SuccessfulRequests++
result.TotalRequests++
mu.Unlock()
fmt.Printf(color.GreenString("Request %d completed in %v\n"), requestNum, elapsed)
fmt.Printf(color.GreenString("Response Status: %v\n"), response.Status)
fmt.Printf(color.GreenString("Response Body: %v\n"), response.Body)
fmt.Printf(color.GreenString("Response Headers: %v\n"), response.Header)
fmt.Println(color.GreenString("--------------------------------------------------"))
successMsg := fmt.Sprintf("Request %d completed in %v\n", requestNum, elapsed)
logAndPrint(color.GreenString, successMsg+fmt.Sprintf("Response Status: %v\n", response.Status)+fmt.Sprintf("Response Body: %v\n", response.Body)+fmt.Sprintf("Response Headers: %v\n", response.Header)+"--------------------------------------------------\n")
}
func logAndPrint(colorFunc func(string, ...interface{}) string, msg string) {
fmt.Print(colorFunc(msg))
log.Println(msg)
file, err := os.OpenFile("request_logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Println("Error opening log file:", err)
return
}
defer file.Close()
if _, err := file.WriteString(msg + "\n"); err != nil {
fmt.Println("Error writing to log file:", err)
}
}
func getDuration() time.Duration {
var durationMillis int
fmt.Print(color.YellowString("Please enter the duration in milliseconds (0 for infinite): "))
_, err := fmt.Scanln(&durationMillis)
if err != nil {
fmt.Println(color.RedString("Invalid duration"))
return 0
}
return time.Duration(durationMillis) * time.Millisecond
}
func runLoadTestWithRate(config LoadTestConfig, duration time.Duration) LoadTestResult {
var wg sync.WaitGroup
var mutex sync.Mutex
var result LoadTestResult
startTime := time.Now()
ticker := time.NewTicker(duration)
defer ticker.Stop()
for i := 1; i <= config.NumRequests; i++ {
wg.Add(1)
go makeRequest(config.URL, config.Method, config.Data, i, &wg, &mutex, &result)
if duration > 0 {
<-ticker.C
}
}
wg.Wait()
result.Duration = time.Since(startTime)
return result
}
func main() {
fmt.Print(`
__ __ _____ __
/ / ____ ____ _ ____/ // ___/ / /_ ____ _____ ____ ___
/ / / __ \ / __ ` + "`" + `// __ / \__ \ / __// __ \ / ___// __ ` + "`" + `__ \
/ /___/ /_/ // /_/ // /_/ / ___/ // /_ / /_/ // / / / / / / /
/_____/\____/ \__,_/ \__,_/ /____/ \__/ \____//_/ /_/ /_/ /_/
`)
fmt.Println(" ")
fmt.Println("Welcome to the Load Test CLI")
fmt.Println(" ")
var url string
fmt.Print(color.YellowString("Please enter the URL to load test: "))
fmt.Scanln(&url)
var numRequests int
fmt.Print(color.YellowString("Please enter the number of requests to send: "))
fmt.Scanln(&numRequests)
var method string
fmt.Print(color.YellowString("Please enter the HTTP method to use(POST/GET/PUT/DELETE): "))
fmt.Scanln(&method)
var data []byte
fmt.Print(color.YellowString("Do you want to send data? (y/n): "))
var sendData string
fmt.Scanln(&sendData)
if sendData == "y" || sendData == "Y" {
fmt.Print(color.YellowString("Please enter the data to send: "))
fmt.Scanln(&data)
}
loadTestConfig := LoadTestConfig{
URL: url,
NumRequests: numRequests,
Method: method,
Data: data,
}
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-stopChan
fmt.Println(color.RedString("Load Test Stopped"))
os.Exit(0)
}()
duration := getDuration()
if duration < 0 {
fmt.Println(color.RedString("Invalid duration"))
return
}
result := runLoadTestWithRate(loadTestConfig, duration)
logFile, err := os.OpenFile("request_logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Println("Error opening log file:", err)
return
}
defer logFile.Close()
log.SetOutput(logFile)
fmt.Printf(color.GreenString("Load Test Completed in %v\n"), result.Duration)
fmt.Printf("Total Requests: %d\n", result.TotalRequests)
fmt.Printf(color.GreenString("Successful Requests: %d\n"), result.SuccessfulRequests)
fmt.Printf(color.RedString("Failed Requests: %d\n"), result.FailedRequests)
fmt.Print("Press ENTER to exit...")
fmt.Scanln()
fmt.Println("Exiting.")
}