├── .gitignore
├── .goreleaser.yaml
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── assets
├── output.png
├── verbose-output.png
├── wscli.gif
└── wscli.png
├── config.yaml
├── docker.sh
├── go.mod
├── go.sum
├── main.go
├── main_test.go
├── pkg
├── config
│ ├── config.go
│ └── getset.go
├── global
│ └── global.go
├── logger
│ └── logger.go
├── perf
│ ├── file.go
│ ├── message.go
│ ├── message_test.go
│ ├── metrics.go
│ ├── perf.go
│ └── tview.go
├── processer
│ └── processor.go
├── terminal
│ ├── terminal.go
│ └── util.go
└── ws
│ └── ws.go
├── server
└── main.go
├── tag.sh
└── test.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # If you prefer the allow list template instead of the deny list, see community template:
2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
3 | #
4 | # Binaries for programs and plugins
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, built with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
17 | # Dependency directories (remove the comment below to include it)
18 | # vendor/
19 |
20 | # Go workspace file
21 | go.work
22 | go.work.sum
23 |
24 | # env file
25 | .env
26 | bin
27 | .vscode
28 |
29 | dist/
30 |
--------------------------------------------------------------------------------
/.goreleaser.yaml:
--------------------------------------------------------------------------------
1 | version: 1
2 |
3 | before:
4 | hooks:
5 | - go mod tidy
6 |
7 | builds:
8 | - env:
9 | - CGO_ENABLED=0
10 | goos:
11 | - linux
12 | - windows
13 | - darwin
14 | goarch:
15 | - amd64
16 | - arm64
17 | - arm
18 | ldflags:
19 | - -s -w # Optional: Strips debug information and reduces binary size
20 | - -X main.CLIVersion={{.Tag}}
21 |
22 | archives:
23 | - format: tar.gz
24 | # this name template makes the OS and Arch compatible with the results of `uname`.
25 | name_template: >-
26 | {{ .ProjectName }}_
27 | {{- title .Os }}_
28 | {{- if eq .Arch "amd64" }}x86_64
29 | {{- else if eq .Arch "386" }}i386
30 | {{- else }}{{ .Arch }}{{ end }}
31 | {{- if .Arm }}v{{ .Arm }}{{ end }}
32 | # use zip for windows archives
33 | format_overrides:
34 | - goos: windows
35 | format: zip
36 |
37 | changelog:
38 | sort: asc
39 | filters:
40 | exclude:
41 | - "^docs:"
42 | - "^test:"
43 |
44 | brews:
45 | - name: wscli@{{.Tag}}
46 | repository:
47 | owner: akshaykhairmode
48 | name: homebrew-tools
49 | homepage: "https://github.com/akshaykhairmode/wscli"
50 | description: "A command-line WebSocket client"
51 | license: "GPL-3.0"
52 | commit_author:
53 | name: Akshay Khairmode
54 | email: akshaykhairmode@gmail.com
55 | commit_msg_template: "Update wscli formula to {{ .Tag }}"
56 | - name: wscli
57 | repository:
58 | owner: akshaykhairmode
59 | name: homebrew-tools
60 | homepage: "https://github.com/akshaykhairmode/wscli"
61 | description: "A command-line WebSocket client"
62 | license: "GPL-3.0"
63 | commit_author:
64 | name: Akshay Khairmode
65 | email: akshaykhairmode@gmail.com
66 | commit_msg_template: "Update wscli formula to {{ .Tag }}"
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:1.24-alpine AS builder
2 |
3 | # Set the working directory inside the container
4 | WORKDIR /app
5 |
6 | # Copy go.mod and go.sum to cache dependencies
7 | COPY go.mod go.sum ./
8 |
9 | # Download all dependencies. Caching is leveraged here.
10 | RUN go mod download
11 |
12 | # Copy the source from the host to the container
13 | COPY . .
14 |
15 | # Build the Go application
16 | ARG GIT_TAG
17 | RUN CGO_ENABLED=0 GOOS=linux go build -ldflags "-X main.CLIVersion=${GIT_TAG} -w -s" -o /app/wscli main.go
18 |
19 | # --- Final Stage ---
20 | FROM alpine:latest
21 |
22 | # Copy the binary from the builder stage
23 | COPY --from=builder /app/wscli /usr/local/bin/wscli
24 |
25 | # Make the binary executable (if necessary, should be done by build stage)
26 | # RUN chmod +x /usr/local/bin/wscli
27 |
28 | # Set the entry point for the container
29 | ENTRYPOINT ["wscli"]
30 |
31 | # Optionally, define the default command arguments
32 | CMD ["--help"]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: release
2 | release:
3 | goreleaser release --clean
4 | bash docker.sh
5 |
6 | .PHONY: test
7 | test:
8 | goreleaser release --snapshot --clean
9 |
10 | .PHONY: lint
11 | lint:
12 | golangci-lint run ./...
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # wscli
2 |
3 | A lightweight and powerful Go command-line tool for interacting with WebSocket servers. Designed for testing, debugging, and scripting, `wscli` provides functionality similar to `wscat` but with additional features. Supports quick load testing.
4 |
5 | ## 🚀 Installation
6 |
7 | ### Using `Docker`
8 | ```sh
9 | $ docker run -it akshaykhairmode/wscli:latest -c "ws://example.com/ws"
10 | ```
11 |
12 | ### Using `go install`
13 | ```sh
14 | go install github.com/akshaykhairmode/wscli@latest
15 | ```
16 |
17 | ### Using `homebrew`
18 | ```sh
19 | brew tap akshaykhairmode/tools
20 | brew install akshaykhairmode/tools/wscli
21 | ```
22 |
23 | ### Download Prebuilt Binaries
24 | If you don’t have Go installed, download the latest binaries from the [Releases Page](https://github.com/akshaykhairmode/wscli/releases).
25 |
26 | ## 🔧 Usage
27 |
28 | ### Connect to a WebSocket server
29 | ```sh
30 | $ wscli -c ws://localhost:8080/ws
31 | ```
32 |
33 | ### Connect with custom headers
34 | ```sh
35 | $ wscli -c ws://localhost:8080/ws -H "Authorization: Bearer mytoken" -H "X-Custom: value"
36 | ```
37 |
38 | ### Send a command immediately after connecting
39 | ```sh
40 | $ wscli -c ws://localhost:8080/ws -x '{"action": "subscribe", "channel": "updates"}'
41 | ```
42 |
43 | ### Send a close message with code 1000 and reason "normal closure"
44 | ```sh
45 | $ wscli --slash -c ws://localhost:8080/ws
46 | /close 1000 normal closure
47 | ```
48 |
49 | ### Send a binary file
50 | ```sh
51 | $ wscli --slash -c ws://localhost:8080/ws
52 | /bfile /home/user/test.bin
53 | ```
54 |
55 | ## ✨ Features
56 |
57 | - **🔹 Native Binaries:** Easy installation across systems.
58 | - **📤 Piped Input:** Send piped input using `|` (disables interactive terminal features).
59 | - **📨 Multiple Messages on Connect:** Send multiple messages immediately after connecting.
60 | - **🎭 Background Execution:**
61 | - Run `wscli` in the background using `nohup`:
62 | ```sh
63 | $ nohup wscli -c ws://localhost/ws -w 1s > nohup.out 2>&1 &
64 | ```
65 | - Redirect output and run in the background:
66 | ```sh
67 | $ wscli -c ws://localhost/ws >> output.txt & 2>&1
68 | ```
69 | - **📜 History Persistence:** Maintain a command history for quick reuse.
70 | - **⚡ Command Execution on Connect:** Use `-x` to execute commands automatically.
71 | - **📌 JSON Pretty Printing:** Format JSON responses using `--jspp`.
72 | - **⌨️ Terminal Shortcuts:** Supports readline shortcuts like `Ctrl+W` (delete word) and `Ctrl+R` (reverse search). [See full list](https://github.com/chzyer/readline/blob/master/doc/shortcut.md).
73 | - **🗂️ Binary File Transfer:** Send a file as a binary message.
74 | - **📊 Load Testing:** Perform load tests using the `--perf` flag.
75 |
76 | ## 🛠 Available Flags
77 |
78 | | Flag | Shorthand | Description |
79 | |------|----------|-------------|
80 | | `--auth` | | HTTP Basic Authentication (`username:password`). |
81 | | `--binary` | `-b` | Send hex-encoded data. |
82 | | `--ca` | | Path to the CA certificate file (optional). |
83 | | `--cert` | | Path to the client certificate file (optional). |
84 | | `--connect` | `-c` | WebSocket connection URL. |
85 | | `--execute` | `-x` | Execute a command after connecting. |
86 | | `--gzipr` | | Enable gzip decoding (server must send messages as binary). |
87 | | `--header` | `-H` | Custom headers (`key:value`). |
88 | | `--help` | `-h` | Show help information. |
89 | | `--jspp` | | Enable JSON pretty printing. |
90 | | `--key` | | Path to the certificate key file (optional). |
91 | | `--no-check` | `-n` | Disable TLS certificate verification. |
92 | | `--no-color` | | Disable colored output. |
93 | | `--origin` | `-o` | Specify origin for the WebSocket connection. |
94 | | `--proxy` | | Use a proxy URL. |
95 | | `--response` | `-r` | Show HTTP response headers. |
96 | | `--show-ping-pong` | `-P` | Show ping/pong messages. |
97 | | `--slash` | | Enable slash commands. |
98 | | `--sub-protocol` | `-s` | Specify a WebSocket sub-protocol. |
99 | | `--verbose` | `-v` | Enable debug logging. |
100 | | `--version` | `-V` | Show version information. |
101 | | `--wait` | `-w` | Wait time after execution (`1s`, `1m`, `1h`). |
102 | | `--print-interval` | | The interval for printing the output. Default is 1s. |
103 | | `--ping-interval` | | The interval for pinging to the connected server. Default is 30s. |
104 | | `--perf` | | Enable performance testing. |
105 | | `--std-out` | | print the received messages in standard output, default is standard error. |
106 |
107 |
108 | ## 🛠 Slash Commands (Enable via `--slash`)
109 |
110 | | Command | Description |
111 | |---------|-------------|
112 | | `/flags` | Show loaded flags. |
113 | | `/ping` | Send a ping message. |
114 | | `/pong` | Send a pong message. |
115 | | `/close` | Send a close message (`/close `). |
116 | | `/bfile` | Send a file (`/bfile `). Max size: 50MB. |
117 |
118 | ## 📊 Load Testing (Enable via `--perf`)
119 |
120 | | Flag | Description | Data Type |
121 | |------|-------------|-----------|
122 | | `--tc` | Total number of connections. | unsigned integer |
123 | | `--lm` | Load message to send. Can use templates defined below. File input supported. | string |
124 | | `--am` | Authentication message. Can use templates defined below. File input supported. | string |
125 | | `--mi` | Message interval. (default: 0s). If not set, then lm will be sent only once. | duration |
126 | | `--waa` | Wait time after authentication before sending load messages. | duration |
127 | | `--wba` | Wait time before sending auth message to the server | duration |
128 | | `--rups` | Connections ramp-up per second (default: 1). | unsigned integer |
129 | | `--outfile` | Do not open the tview output and write the output to file. | string |
130 | | `--pconfig` | Take perf config from file. Pass the file path here. The format of the file is available [here](config.yaml). This will override all other perf flags even if set. | string |
131 |
132 | **Note**: `--lm` and `--am` also support file input. Provide an absolute path to send messages from a file. The file reading will restart from the first line when EOF is reached. If file is less than 10MB then we store it in memory. "\n" is the delimeter.
133 |
134 | ### Load Message Templates
135 |
136 | | **Function** | **Description** | **Parameters** | **Data Types** |
137 | |---------------------------------------|------------------------------------------------------------------------------------------------------------------|------------------------------------|--------------------------------|
138 | | `RandomNum` | Generates a random number between 0 and `` (default range: 0–10,000). | `` (optional) | Integer |
139 | | `RandomUUID` | Generates a random UUID. | None | N/A |
140 | | `RandomAN` | Generates a random alphanumeric string with the specified `` (default: 10 characters). | `` (optional) | Integer |
141 | | `UniqSeq` | Generates a unique atomic sequence within a specified ``. Multiple connections share the same sequence when using the same group. The `` value sets the initial number (default: 0). If different start values are provided, the first one is used. Examples:
- `{{UniqSeq "1" 10}} != {{UniqSeq "1" 10}}` (Not the same number)
- `{{UniqSeq "0"}} == {{UniqSeq "1"}}` (Different groups generate the same number) | ``
`` (optional) | String
Integer |
142 | | `.Seq` | Generates a sequence starting from 0 for each connection. No shared counters. | | |
143 |
144 |
145 |
146 | #### Example
147 | ```sh
148 | $ wscli -c ws://localhost:8080/ws --perf --tc 1000 --lm "hello world {{RandomNum 50}}" --rups 100 --mi 1s
149 |
150 | OR
151 |
152 | $ wscli -c ws://localhost:8080/ws --perf --tc 1000 --lm "/tmp/load.txt" --rups 100 --mi 1s
153 |
154 | # Flags used:
155 | # --perf (enable performance testing)
156 | # --tc 1000 (create 1000 connections)
157 | # --lm "hello world {{RandomNumber 50}}" (load message, generate a random number from 0 to 50)
158 | # --lm "/tmp/load.txt" (load message, read from file)
159 | # --rups 100 (ramp up 100 connections per second)
160 | # --mi 1s (send 1 message per second)
161 | ```
162 |
163 | **Normal Output**
164 |
165 | 
166 |
167 | **Perf output**:
168 |
169 | 
170 |
171 | **Perf Verbose output**:
172 |
173 | 
174 |
175 | **Demo**
176 |
177 | 
178 |
--------------------------------------------------------------------------------
/assets/output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshaykhairmode/wscli/b63540ada4b99fa65f25047e0e643959bc96bb08/assets/output.png
--------------------------------------------------------------------------------
/assets/verbose-output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshaykhairmode/wscli/b63540ada4b99fa65f25047e0e643959bc96bb08/assets/verbose-output.png
--------------------------------------------------------------------------------
/assets/wscli.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshaykhairmode/wscli/b63540ada4b99fa65f25047e0e643959bc96bb08/assets/wscli.gif
--------------------------------------------------------------------------------
/assets/wscli.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshaykhairmode/wscli/b63540ada4b99fa65f25047e0e643959bc96bb08/assets/wscli.png
--------------------------------------------------------------------------------
/config.yaml:
--------------------------------------------------------------------------------
1 | tc: 100 #total number of connections.
2 | lm: "Hello, server!" #the message which needs to be sent.
3 | mps: 0 #message per second. When set to 0 will send the message only once.
4 | am: "AUTH user:password" #Auth Message
5 | wba: 5s #wait before sending authorization.
6 | waa: 2s #wait after sending authorization.
7 | rups: 1 #ramp up per second
8 | outfile: "" #if empty will open tview, else will write the output to given file.
--------------------------------------------------------------------------------
/docker.sh:
--------------------------------------------------------------------------------
1 | echo "$DOCKER_PASSWORD" | docker login -u akshaykhairmode --password-stdin
2 | tag=$(git describe --tags --abbrev=0)
3 | docker build --build-arg GIT_TAG=$tag -t akshaykhairmode/wscli:$tag -t akshaykhairmode/wscli:latest .
4 | docker push akshaykhairmode/wscli:$tag
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/akshaykhairmode/wscli
2 |
3 | go 1.24.1
4 |
5 | require (
6 | github.com/chzyer/readline v1.5.1
7 | github.com/fatih/color v1.18.0
8 | github.com/gdamore/tcell/v2 v2.7.1
9 | github.com/google/uuid v1.6.0
10 | github.com/gorilla/websocket v1.5.3
11 | github.com/lesismal/nbio v1.6.2
12 | github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475
13 | github.com/rivo/tview v0.0.0-20241227133733-17b7edb88c57
14 | github.com/rs/zerolog v1.33.0
15 | github.com/spf13/pflag v1.0.6
16 | gopkg.in/yaml.v3 v3.0.1
17 | )
18 |
19 | require (
20 | github.com/gdamore/encoding v1.0.0 // indirect
21 | github.com/lesismal/llib v1.2.1 // indirect
22 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
23 | github.com/mattn/go-colorable v0.1.13 // indirect
24 | github.com/mattn/go-isatty v0.0.20 // indirect
25 | github.com/mattn/go-runewidth v0.0.15 // indirect
26 | github.com/rivo/uniseg v0.4.7 // indirect
27 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
28 | golang.org/x/sys v0.25.0 // indirect
29 | golang.org/x/term v0.17.0 // indirect
30 | golang.org/x/text v0.14.0 // indirect
31 | )
32 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM=
2 | github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ=
3 | github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI=
4 | github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
5 | github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04=
6 | github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
7 | github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
8 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
9 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
10 | github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
11 | github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
12 | github.com/gdamore/tcell/v2 v2.7.1 h1:TiCcmpWHiAU7F0rA2I3S2Y4mmLmO9KHxJ7E1QhYzQbc=
13 | github.com/gdamore/tcell/v2 v2.7.1/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg=
14 | github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
15 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
16 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
17 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
18 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
19 | github.com/lesismal/llib v1.2.1 h1:Cz/ZoCYhsLAr3A67K2DlHnsp/O7G2j+eTWmiKUu3WuE=
20 | github.com/lesismal/llib v1.2.1/go.mod h1:70tFXXe7P1FZ02AU9l8LgSOK7d7sRrpnkUr3rd3gKSg=
21 | github.com/lesismal/nbio v1.6.2 h1:vcjLDtF8mqQisbX9dYiShs+If7q+G4XXvjBKry51lZY=
22 | github.com/lesismal/nbio v1.6.2/go.mod h1:4Nz9So5nq8P4NpLT41M2WKZg9ZkiX1Ai7nH2XJagnmU=
23 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
24 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
25 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
26 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
27 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
28 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
29 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
30 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
31 | github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
32 | github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
33 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
34 | github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
35 | github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
36 | github.com/rivo/tview v0.0.0-20241227133733-17b7edb88c57 h1:LmsF7Fk5jyEDhJk0fYIqdWNuTxSyid2W42A0L2YWjGE=
37 | github.com/rivo/tview v0.0.0-20241227133733-17b7edb88c57/go.mod h1:02iFIz7K/A9jGCvrizLPvoqr4cEIx7q54RH5Qudkrss=
38 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
39 | github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
40 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
41 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
42 | github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
43 | github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
44 | github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
45 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
46 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
47 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
48 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
49 | golang.org/x/crypto v0.0.0-20210513122933-cd7d49e622d5/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
50 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
51 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
52 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
53 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
54 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
55 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
56 | golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
57 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
58 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
59 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
60 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
61 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
62 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
63 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
64 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
65 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
66 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
67 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
68 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
69 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
70 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
71 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
72 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
73 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
74 | golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
75 | golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
76 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
77 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
78 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
79 | golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U=
80 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
81 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
82 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
83 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
84 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
85 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
86 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
87 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
88 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
89 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
90 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
91 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
92 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
93 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
94 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
95 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
96 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
97 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 |
8 | "github.com/akshaykhairmode/wscli/pkg/config"
9 | "github.com/akshaykhairmode/wscli/pkg/global"
10 | "github.com/akshaykhairmode/wscli/pkg/logger"
11 | "github.com/akshaykhairmode/wscli/pkg/perf"
12 | "github.com/akshaykhairmode/wscli/pkg/processer"
13 | "github.com/akshaykhairmode/wscli/pkg/terminal"
14 | "github.com/akshaykhairmode/wscli/pkg/ws"
15 | )
16 |
17 | var CLIVersion string
18 |
19 | func main() {
20 |
21 | log.SetOutput(os.Stderr)
22 | if config.Flags.IsStdOut {
23 | log.SetOutput(os.Stdout)
24 | }
25 | log.SetFlags(0)
26 |
27 | logger.Init(os.Stdout, nil)
28 |
29 | if config.Flags.Version {
30 | fmt.Printf("CLI Version : %s\n", CLIVersion)
31 | return
32 | }
33 |
34 | if config.Flags.IsPerf {
35 | gen, err := perf.New()
36 | if err != nil {
37 | logger.Fatal().Err(err).Msg("error while creating perf instance")
38 | }
39 |
40 | gen.Run(config.Flags.Perf.LogOutFile == "")
41 | return
42 | }
43 |
44 | conn, closeFunc, readFunc, err := ws.Connect()
45 | if err != nil {
46 | logger.Fatal().Err(err).Msg("connect err")
47 | }
48 |
49 | defer closeFunc()
50 |
51 | go readFunc(conn)
52 |
53 | if config.Flags.ShouldProcessAsCmd() {
54 | processer.ProcessAsCmd(conn)
55 | return
56 | }
57 |
58 | term, closef, wg := terminal.New()
59 | defer func() {
60 | if err := closef(); err != nil {
61 | logger.Debug().Err(err).Msg("error while closing readline")
62 | }
63 | }()
64 |
65 | go func() {
66 | global.WaitForStop()
67 | term.Close()
68 | }()
69 |
70 | processer.New(conn, term).Process()
71 |
72 | term.Reader(wg)
73 |
74 | fmt.Println()
75 | }
76 |
--------------------------------------------------------------------------------
/main_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os/exec"
6 | "testing"
7 | "time"
8 | )
9 |
10 | func getExecuteParams() []string {
11 | return []string{"run", "main.go", "-c", "ws://localhost:8080/ws", "-w", "5s", "-x", "hello world"}
12 | }
13 |
14 | func TestExecute(t *testing.T) {
15 |
16 | now := time.Now()
17 |
18 | cmd := exec.Command("go", getExecuteParams()...)
19 | output, err := cmd.CombinedOutput()
20 | if err != nil {
21 | t.Error(err)
22 | return
23 | }
24 |
25 | if time.Since(now) < 5*time.Second {
26 | t.Error("program did not wait for 5seconds")
27 | }
28 |
29 | fmt.Println(string(output))
30 |
31 | if string(output) != "« hello world\n" {
32 | t.Error("output does not match")
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/pkg/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 | "time"
8 |
9 | "github.com/fatih/color"
10 | "github.com/spf13/pflag"
11 | )
12 |
13 | type Flag struct {
14 | ConnectURL string
15 | Auth string
16 | Headers []string
17 | Origin string
18 | Execute []string
19 | Wait time.Duration
20 | PrintOutputInterval time.Duration
21 | PingInterval time.Duration
22 | SubProtocol []string
23 | Proxy string
24 |
25 | Perf Perf
26 |
27 | ShowPingPong bool
28 | IsSlash bool
29 | NoCertificateCheck bool
30 | Version bool
31 | Verbose bool
32 | NoColor bool
33 | ShouldShowResponseHeaders bool
34 | IsJSONPrettyPrint bool
35 | IsBinary bool
36 | IsGzipResponse bool
37 | IsPerf bool
38 |
39 | IsStdOut bool
40 |
41 | Help bool
42 | IsSTDin bool // read from stdin, cannot send messages to the server other than what is in the stdin
43 |
44 | TLS TLS
45 | }
46 |
47 | type TLS struct {
48 | CA string
49 | Cert string
50 | Key string
51 | Passphrase string
52 | }
53 |
54 | type Perf struct {
55 | TotalConns uint `yaml:"tc"` //total connections which needs to be created.
56 | LoadMessage string `yaml:"lm"` //the load message which needs to be sent to the server.
57 | MessageInterval time.Duration `yaml:"mi"` //at what interval we send the messages.
58 | AuthMessage string `yaml:"am"` //the auth message which needs to be send as soon as connecting.
59 | WaitBeforeAuth time.Duration `yaml:"wba"` //wait for x amount of time before sending auth message
60 | WaitAfterAuth time.Duration `yaml:"waa"` //wait for x amount of time before starting to send load.
61 | RampUpConnsPerSecond uint `yaml:"rups"` //how many connections to add every second
62 | LogOutFile string `yaml:"outfile"` //give the file path where to write the logs
63 | ConfigPath string //the file path from where to get the perf config
64 | }
65 |
66 | func (p Perf) String() string {
67 | return fmt.Sprintf(`Total Connections: %d, Messages Interval: %s, Wait Before Auth: %s, Wait After Auth: %s
68 | Ramp Up Connections Per Second: %d, Log Out File: %s, Auth Message: %s, Load Message: %s
69 | ConfigPath : %s`,
70 | p.TotalConns,
71 | p.MessageInterval,
72 | p.WaitBeforeAuth,
73 | p.WaitAfterAuth,
74 | p.RampUpConnsPerSecond,
75 | p.LogOutFile,
76 | p.AuthMessage,
77 | p.LoadMessage,
78 | p.ConfigPath,
79 | )
80 | }
81 |
82 | var Flags *Flag
83 |
84 | func init() {
85 | Flags = get()
86 | }
87 |
88 | func get() *Flag {
89 | cfg := Flag{}
90 |
91 | pflag.BoolVarP(&cfg.Help, "help", "h", false, " Display help information.")
92 | pflag.BoolVar(&cfg.IsSlash, "slash", false, "Enable slash commands (Experimental).")
93 | pflag.BoolVarP(&cfg.NoCertificateCheck, "no-check", "n", false, "Disable TLS certificate verification.")
94 | pflag.BoolVarP(&cfg.ShowPingPong, "show-ping-pong", "P", false, "Show ping/pong messages.")
95 | pflag.BoolVarP(&cfg.Version, "version", "V", false, "Display version information.")
96 | pflag.BoolVarP(&cfg.Verbose, "verbose", "v", false, "Enable debug logging.")
97 | pflag.BoolVar(&cfg.NoColor, "no-color", false, "Disable colored output.")
98 | pflag.BoolVarP(&cfg.ShouldShowResponseHeaders, "response", "r", false, "Display HTTP response headers from the server.")
99 | pflag.BoolVar(&cfg.IsJSONPrettyPrint, "jspp", false, "Enable JSON pretty printing for responses.")
100 | pflag.BoolVarP(&cfg.IsBinary, "binary", "b", false, "Send hex encoded data to server")
101 | pflag.BoolVar(&cfg.IsGzipResponse, "gzipr", false, "Enable gzip decoding if server messages are gzip-encoded. (Note: Server must send messages as binary.)")
102 | pflag.BoolVar(&cfg.IsStdOut, "std-out", false, "print the received messages in standard output, default is standard error")
103 |
104 | pflag.StringVarP(&cfg.ConnectURL, "connect", "c", "", "WebSocket connection URL.")
105 | pflag.StringVar(&cfg.Proxy, "proxy", "", "Use a proxy URL.")
106 | pflag.StringVar(&cfg.Auth, "auth", "", "HTTP Basic Authentication credentials (e.g., username:password).")
107 | pflag.StringSliceVarP(&cfg.Headers, "header", "H", []string{}, "Custom headers (key:value, can be used multiple times).")
108 | pflag.StringVarP(&cfg.Origin, "origin", "o", "", "Specify origin for the WebSocket connection (optional).")
109 | pflag.StringSliceVarP(&cfg.Execute, "execute", "x", []string{}, "Execute a command after connecting (use multiple times for multiple commands).")
110 | pflag.DurationVarP(&cfg.Wait, "wait", "w", 0, "Wait time after command execution (1s, 1m, 1h).")
111 | pflag.StringSliceVarP(&cfg.SubProtocol, "sub-protocol", "s", []string{}, "Specify a sub-protocol for the WebSocket connection (optional, can be used multiple times).")
112 | pflag.DurationVar(&cfg.PrintOutputInterval, "print-interval", time.Second, "how often to print the status on the terminal")
113 | pflag.DurationVar(&cfg.PingInterval, "ping-interval", 30*time.Second, "how often to ping the connections which are created")
114 |
115 | pflag.StringVar(&cfg.TLS.CA, "ca", "", "Path to the CA certificate file (optional).")
116 | pflag.StringVar(&cfg.TLS.Cert, "cert", "", "Path to the client certificate file (optional).")
117 | pflag.StringVar(&cfg.TLS.Key, "key", "", "Path to the certificate key file (optional).")
118 |
119 | //perf
120 | pflag.BoolVar(&cfg.IsPerf, "perf", false, "Enable load testing")
121 | pflag.StringVar(&cfg.Perf.ConfigPath, "pconfig", "", "Load perf config from file")
122 | pflag.UintVar(&cfg.Perf.TotalConns, "tc", 0, "Total number of connections to create")
123 | pflag.StringVar(&cfg.Perf.LoadMessage, "lm", "", "Load message to send to the server")
124 | pflag.DurationVar(&cfg.Perf.MessageInterval, "mi", 0, "the interval for sending messages.")
125 | pflag.StringVar(&cfg.Perf.AuthMessage, "am", "", "Authentication message to send to the server")
126 | pflag.DurationVar(&cfg.Perf.WaitAfterAuth, "waa", 0, "Wait time after authentication before sending load messages to server")
127 | pflag.DurationVar(&cfg.Perf.WaitBeforeAuth, "wba", 0, "Wait time before sending authentication to server")
128 | pflag.UintVar(&cfg.Perf.RampUpConnsPerSecond, "rups", 1, "Number of connections to ramp up per second")
129 | pflag.StringVar(&cfg.Perf.LogOutFile, "outfile", "", "Write to file instead of output on terminal")
130 |
131 | pflag.Parse()
132 |
133 | if cfg.Help {
134 | pflag.Usage()
135 | os.Exit(0)
136 | }
137 |
138 | if cfg.NoColor {
139 | color.NoColor = true
140 | }
141 |
142 | cfg.IsSTDin = isInputFromPipe()
143 |
144 | return &cfg
145 | }
146 |
147 | var IsSTDoutRedirected bool
148 |
149 | func init() {
150 | fi, err := os.Stdout.Stat()
151 | if err != nil {
152 | IsSTDoutRedirected = false
153 | return
154 | }
155 |
156 | IsSTDoutRedirected = fi.Mode().IsRegular()
157 | }
158 |
159 | func isInputFromPipe() bool {
160 | fileInfo, err := os.Stdin.Stat()
161 | if err != nil {
162 | return false
163 | }
164 | return (fileInfo.Mode() & os.ModeCharDevice) == 0
165 | }
166 |
167 | func (c *Flag) String() string {
168 | var sb strings.Builder
169 |
170 | sb.WriteString("Config:\n")
171 | sb.WriteString(fmt.Sprintf(" ConnectURL: %s\n", c.ConnectURL))
172 | sb.WriteString(fmt.Sprintf(" Auth: %s\n", c.Auth))
173 | sb.WriteString(fmt.Sprintf(" Headers: %v\n", c.Headers))
174 | sb.WriteString(fmt.Sprintf(" Origin: %s\n", c.Origin))
175 | sb.WriteString(fmt.Sprintf(" Execute: %v\n", c.Execute))
176 | sb.WriteString(fmt.Sprintf(" Wait: %s\n", c.Wait))
177 | sb.WriteString(fmt.Sprintf(" PrintOutputInterval: %s\n", c.PrintOutputInterval)) // Added
178 | sb.WriteString(fmt.Sprintf(" PingInterval: %s\n", c.PingInterval)) // Added
179 | sb.WriteString(fmt.Sprintf(" SubProtocol: %v\n", c.SubProtocol))
180 | sb.WriteString(fmt.Sprintf(" Proxy: %s\n", c.Proxy))
181 |
182 | sb.WriteString(fmt.Sprintf(" ShowPingPong: %t\n", c.ShowPingPong))
183 | sb.WriteString(fmt.Sprintf(" IsSlash: %t\n", c.IsSlash))
184 | sb.WriteString(fmt.Sprintf(" NoCertificateCheck: %t\n", c.NoCertificateCheck))
185 | sb.WriteString(fmt.Sprintf(" Version: %t\n", c.Version))
186 | sb.WriteString(fmt.Sprintf(" Verbose: %t\n", c.Verbose))
187 | sb.WriteString(fmt.Sprintf(" NoColor: %t\n", c.NoColor))
188 | sb.WriteString(fmt.Sprintf(" ShouldShowResponseHeaders: %t\n", c.ShouldShowResponseHeaders))
189 | sb.WriteString(fmt.Sprintf(" IsJSONPrettyPrint: %t\n", c.IsJSONPrettyPrint))
190 | sb.WriteString(fmt.Sprintf(" IsBinary: %t\n", c.IsBinary))
191 | sb.WriteString(fmt.Sprintf(" IsGzipResponse: %t\n", c.IsGzipResponse))
192 | sb.WriteString(fmt.Sprintf(" IsPerf: %t\n", c.IsPerf)) // Added
193 | sb.WriteString(fmt.Sprintf(" IsStdOut: %t\n", c.IsStdOut)) // Added
194 |
195 | sb.WriteString(fmt.Sprintf(" Help: %t\n", c.Help))
196 | sb.WriteString(fmt.Sprintf(" IsSTDin: %t\n", c.IsSTDin))
197 |
198 | sb.WriteString(fmt.Sprintf(" TLS: %+v\n", c.TLS))
199 | if c.IsPerf { // Added Perf details conditionally
200 | sb.WriteString(" Perf Config:\n")
201 | // Indent the Perf string output for better readability
202 | perfLines := strings.Split(c.Perf.String(), "\n")
203 | for _, line := range perfLines {
204 | sb.WriteString(fmt.Sprintf(" %s\n", strings.TrimSpace(line)))
205 | }
206 | }
207 |
208 | return sb.String()
209 | }
210 |
--------------------------------------------------------------------------------
/pkg/config/getset.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | // func (c *Flag) IsPerf() bool {
4 | // c.mux.RLock()
5 | // defer c.mux.RUnlock()
6 | // return c.isPerf
7 | // }
8 |
9 | // func (c *Flag) SetPerf(isPerf bool) {
10 | // c.mux.Lock()
11 | // defer c.mux.Unlock()
12 | // c.isPerf = isPerf
13 | // }
14 |
15 | // func (c *Flag) GetPerfConfig() Perf {
16 | // c.mux.RLock()
17 | // defer c.mux.RUnlock()
18 | // return c.perf
19 | // }
20 |
21 | // func (c *Flag) SetPerfConfig(perf Perf) {
22 | // c.mux.Lock()
23 | // defer c.mux.Unlock()
24 | // c.perf = perf
25 | // }
26 |
27 | // func (c *Flag) GetConnectURL() string {
28 | // c.mux.RLock()
29 | // defer c.mux.RUnlock()
30 | // return c.connectURL
31 | // }
32 |
33 | // func (c *Flag) SetConnectURL(connectURL string) {
34 | // c.mux.Lock()
35 | // defer c.mux.Unlock()
36 | // c.connectURL = connectURL
37 | // }
38 |
39 | // func (c *Flag) GetAuth() string {
40 | // c.mux.RLock()
41 | // defer c.mux.RUnlock()
42 | // return c.auth
43 | // }
44 |
45 | // func (c *Flag) SetAuth(auth string) {
46 | // c.mux.Lock()
47 | // defer c.mux.Unlock()
48 | // c.auth = auth
49 | // }
50 |
51 | // func (c *Flag) GetHeaders() []string {
52 | // c.mux.RLock()
53 | // defer c.mux.RUnlock()
54 | // return c.headers
55 | // }
56 |
57 | // func (c *Flag) SetHeaders(headers []string) {
58 | // c.mux.Lock()
59 | // defer c.mux.Unlock()
60 | // c.headers = headers
61 | // }
62 |
63 | // func (c *Flag) GetOrigin() string {
64 | // c.mux.RLock()
65 | // defer c.mux.RUnlock()
66 | // return c.origin
67 | // }
68 |
69 | // func (c *Flag) SetOrigin(origin string) {
70 | // c.mux.Lock()
71 | // defer c.mux.Unlock()
72 | // c.origin = origin
73 | // }
74 |
75 | // func (c *Flag) GetExecute() []string {
76 | // c.mux.RLock()
77 | // defer c.mux.RUnlock()
78 | // return c.execute
79 | // }
80 |
81 | // func (c *Flag) SetExecute(execute []string) {
82 | // c.mux.Lock()
83 | // defer c.mux.Unlock()
84 | // c.execute = execute
85 | // }
86 |
87 | // func (c *Flag) GetWait() time.Duration {
88 | // c.mux.RLock()
89 | // defer c.mux.RUnlock()
90 | // return c.wait
91 | // }
92 |
93 | // func (c *Flag) SetWait(wait time.Duration) {
94 | // c.mux.Lock()
95 | // defer c.mux.Unlock()
96 | // c.wait = wait
97 | // }
98 |
99 | // func (c *Flag) GetSubProtocol() []string {
100 | // c.mux.RLock()
101 | // defer c.mux.RUnlock()
102 | // return c.subProtocol
103 | // }
104 |
105 | // func (c *Flag) SetSubProtocol(subProtocol []string) {
106 | // c.mux.Lock()
107 | // defer c.mux.Unlock()
108 | // c.subProtocol = subProtocol
109 | // }
110 |
111 | // func (c *Flag) GetProxy() string {
112 | // c.mux.RLock()
113 | // defer c.mux.RUnlock()
114 | // return c.proxy
115 | // }
116 |
117 | // func (c *Flag) SetProxy(proxy string) {
118 | // c.mux.Lock()
119 | // defer c.mux.Unlock()
120 | // c.proxy = proxy
121 | // }
122 |
123 | // func (c *Flag) ShowPingPong() bool {
124 | // c.mux.RLock()
125 | // defer c.mux.RUnlock()
126 | // return c.showPingPong
127 | // }
128 |
129 | // func (c *Flag) SetShowPingPong(showPingPong bool) {
130 | // c.mux.Lock()
131 | // defer c.mux.Unlock()
132 | // c.showPingPong = showPingPong
133 | // }
134 |
135 | // func (c *Flag) IsSlash() bool {
136 | // c.mux.RLock()
137 | // defer c.mux.RUnlock()
138 | // return c.isSlash
139 | // }
140 |
141 | // func (c *Flag) SetIsSlash(isSlash bool) {
142 | // c.mux.Lock()
143 | // defer c.mux.Unlock()
144 | // c.isSlash = isSlash
145 | // }
146 |
147 | // func (c *Flag) SkipCertificateCheck() bool {
148 | // c.mux.RLock()
149 | // defer c.mux.RUnlock()
150 | // return c.noCertificateCheck
151 | // }
152 |
153 | // func (c *Flag) SetNoCertificateCheck(noCertificateCheck bool) {
154 | // c.mux.Lock()
155 | // defer c.mux.Unlock()
156 | // c.noCertificateCheck = noCertificateCheck
157 | // }
158 |
159 | // func (c *Flag) IsShowVersion() bool {
160 | // c.mux.RLock()
161 | // defer c.mux.RUnlock()
162 | // return c.version
163 | // }
164 |
165 | // func (c *Flag) SetVersion(version bool) {
166 | // c.mux.Lock()
167 | // defer c.mux.Unlock()
168 | // c.version = version
169 | // }
170 |
171 | // func (c *Flag) IsVerbose() bool {
172 | // c.mux.RLock()
173 | // defer c.mux.RUnlock()
174 | // return c.verbose
175 | // }
176 |
177 | // func (c *Flag) SetVerbose(verbose bool) {
178 | // c.mux.Lock()
179 | // defer c.mux.Unlock()
180 | // c.verbose = verbose
181 | // }
182 |
183 | // func (c *Flag) IsNoColor() bool {
184 | // c.mux.RLock()
185 | // defer c.mux.RUnlock()
186 | // return c.noColor
187 | // }
188 |
189 | // func (c *Flag) SetNoColor(noColor bool) {
190 | // c.mux.Lock()
191 | // defer c.mux.Unlock()
192 | // c.noColor = noColor
193 | // }
194 |
195 | // func (c *Flag) ShowResponseHeaders() bool {
196 | // c.mux.RLock()
197 | // defer c.mux.RUnlock()
198 | // return c.shouldShowResponseHeaders
199 | // }
200 |
201 | // func (c *Flag) SetResponse(response bool) {
202 | // c.mux.Lock()
203 | // defer c.mux.Unlock()
204 | // c.shouldShowResponseHeaders = response
205 | // }
206 |
207 | // func (c *Flag) IsJSONPrettyPrint() bool {
208 | // c.mux.RLock()
209 | // defer c.mux.RUnlock()
210 | // return c.isJSONPrettyPrint
211 | // }
212 |
213 | // func (c *Flag) SetJSONPrettyPrint(jSONPrettyPrint bool) {
214 | // c.mux.Lock()
215 | // defer c.mux.Unlock()
216 | // c.isJSONPrettyPrint = jSONPrettyPrint
217 | // }
218 |
219 | // func (c *Flag) IsBinary() bool {
220 | // c.mux.RLock()
221 | // defer c.mux.RUnlock()
222 | // return c.isBinary
223 | // }
224 |
225 | // func (c *Flag) SetIsBinary(isBinary bool) {
226 | // c.mux.Lock()
227 | // defer c.mux.Unlock()
228 | // c.isBinary = isBinary
229 | // }
230 |
231 | // func (c *Flag) IsHelp() bool {
232 | // c.mux.RLock()
233 | // defer c.mux.RUnlock()
234 | // return c.help
235 | // }
236 |
237 | // func (c *Flag) SetHelp(help bool) {
238 | // c.mux.Lock()
239 | // defer c.mux.Unlock()
240 | // c.help = help
241 | // }
242 |
243 | // func (c *Flag) IsStdin() bool {
244 | // c.mux.RLock()
245 | // defer c.mux.RUnlock()
246 | // return c.isSTDin
247 | // }
248 |
249 | // func (c *Flag) SetStdin(stdin bool) {
250 | // c.mux.Lock()
251 | // defer c.mux.Unlock()
252 | // c.isSTDin = stdin
253 | // }
254 |
255 | // func (c *Flag) IsGzipResponse() bool {
256 | // c.mux.RLock()
257 | // defer c.mux.RUnlock()
258 | // return c.isGzipResponse
259 | // }
260 |
261 | // func (c *Flag) IsStdOut() bool {
262 | // c.mux.RLock()
263 | // defer c.mux.RUnlock()
264 | // return c.isStdOut
265 | // }
266 |
267 | // func (c *Flag) SetGzipResponse(gzipr bool) {
268 | // c.mux.Lock()
269 | // defer c.mux.Unlock()
270 | // c.isGzipResponse = gzipr
271 | // }
272 |
273 | // func (c *Flag) GetTLS() TLS {
274 | // c.mux.RLock()
275 | // defer c.mux.RUnlock()
276 | // return c.tls
277 | // }
278 |
279 | // func (c *Flag) SetTLS(tls TLS) {
280 | // c.mux.Lock()
281 | // defer c.mux.Unlock()
282 | // c.tls = tls
283 | // }
284 |
285 | // // Getters and Setters for TLS
286 |
287 | // func (t *TLS) GetCA() string {
288 | // return t.CA
289 | // }
290 |
291 | // func (t *TLS) SetCA(ca string) {
292 | // t.CA = ca
293 | // }
294 |
295 | // func (t *TLS) GetCert() string {
296 | // return t.Cert
297 | // }
298 |
299 | // func (t *TLS) SetCert(cert string) {
300 | // t.Cert = cert
301 | // }
302 |
303 | // func (c *Flag) GetPingInterval() time.Duration {
304 | // c.mux.RLock()
305 | // defer c.mux.RUnlock()
306 | // return c.pingInterval
307 | // }
308 |
309 | func (c *Flag) ShouldProcessAsCmd() bool {
310 | if len(Flags.Execute) > 0 && Flags.Wait > 0 {
311 | return true
312 | }
313 |
314 | if Flags.IsSTDin {
315 | return true
316 | }
317 |
318 | return false
319 | }
320 |
321 | // func (c *Flag) GetPrintInterval() time.Duration {
322 | // c.mux.RLock()
323 | // defer c.mux.RUnlock()
324 | // return c.printOutputInterval
325 | // }
326 |
327 | // func (c *Flag) SetPrintInterval(dur time.Duration) {
328 | // c.printOutputInterval = dur
329 | // }
330 |
331 | // func (c *Flag) GetPerfOutfile() string {
332 | // c.mux.RLock()
333 | // defer c.mux.RUnlock()
334 | // return c.perf.LogOutFile
335 | // }
336 |
337 | // func (c *Flag) SetPerfOutfile(file string) {
338 | // c.mux.Lock()
339 | // defer c.mux.Unlock()
340 | // c.perf.LogOutFile = file
341 | // }
342 |
--------------------------------------------------------------------------------
/pkg/global/global.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | var stopApp = make(chan struct{}, 2)
4 |
5 | func Stop() {
6 | stopApp <- struct{}{}
7 | }
8 |
9 | func WaitForStop() {
10 | <-stopApp
11 | }
12 |
--------------------------------------------------------------------------------
/pkg/logger/logger.go:
--------------------------------------------------------------------------------
1 | package logger
2 |
3 | import (
4 | "io"
5 | "strings"
6 | "time"
7 |
8 | "github.com/akshaykhairmode/wscli/pkg/config"
9 | "github.com/rs/zerolog"
10 | )
11 |
12 | var globalLogger *zerolog.Logger
13 |
14 | var defaultFormatLevelFunc = func(i any) string {
15 | level := strings.ToUpper(i.(string))
16 | switch level {
17 | case "ERROR":
18 | return "[red]" + level + "[white]"
19 | case "DEBUG":
20 | return "[gray]" + level + "[white]"
21 | case "INFO":
22 | return "[blue]" + level + "[white]"
23 | }
24 | return level
25 | }
26 |
27 | func Init(out io.Writer, formatLevelFunc func(i any) string) {
28 |
29 | if formatLevelFunc == nil {
30 | formatLevelFunc = defaultFormatLevelFunc
31 | }
32 |
33 | consoleWriter := zerolog.ConsoleWriter{
34 | Out: out,
35 | NoColor: true,
36 | FormatLevel: formatLevelFunc,
37 | FormatTimestamp: func(i any) string {
38 | return time.Now().Format("15:04:05.000")
39 | },
40 | }
41 |
42 | l := zerolog.New(consoleWriter).With().Logger()
43 |
44 | if config.Flags.Verbose {
45 | l = l.Level(zerolog.DebugLevel)
46 | } else {
47 | l = l.Level(zerolog.InfoLevel)
48 | }
49 |
50 | globalLogger = &l
51 |
52 | }
53 |
54 | func Debug() *zerolog.Event {
55 | return globalLogger.Debug()
56 | }
57 |
58 | func Fatal() *zerolog.Event {
59 | return globalLogger.Fatal()
60 | }
61 |
62 | func Error() *zerolog.Event {
63 | return globalLogger.Error()
64 | }
65 |
66 | func Info() *zerolog.Event {
67 | return globalLogger.Info()
68 | }
69 |
70 | func Err(err error) *zerolog.Event {
71 | return globalLogger.Err(err)
72 | }
73 |
--------------------------------------------------------------------------------
/pkg/perf/file.go:
--------------------------------------------------------------------------------
1 | package perf
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 | "text/tabwriter"
8 | "time"
9 |
10 | "github.com/akshaykhairmode/wscli/pkg/logger"
11 | )
12 |
13 | type FileOutput struct {
14 | f *os.File
15 | w *tabwriter.Writer
16 | }
17 |
18 | func NewFileOutput(path string) *FileOutput {
19 | f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_TRUNC, 0644)
20 | if err != nil {
21 | logger.Fatal().Err(err).Msg("error while opening the output file")
22 | }
23 |
24 | w := tabwriter.NewWriter(f, 0, 0, 2, ' ', tabwriter.AlignRight|tabwriter.Debug)
25 |
26 | out := &FileOutput{
27 | f: f,
28 | w: w,
29 | }
30 |
31 | return out
32 | }
33 |
34 | func (fo *FileOutput) tWrite(data string) {
35 | _, err := fo.w.Write(fmt.Appendf(nil, "%s\t", data))
36 | if err != nil {
37 | logger.Err(err).Msg("error while writing to tabwriter")
38 | }
39 | }
40 |
41 | func (fo *FileOutput) UpdateTableAndLogs(data []string, errors *errMsg) {
42 |
43 | //Stats
44 | for _, heading := range headings {
45 | fo.tWrite(heading)
46 | }
47 |
48 | fo.tWrite("\n")
49 |
50 | for _, value := range data {
51 | fo.tWrite(value)
52 | }
53 |
54 | fo.tWrite("\n")
55 |
56 | defer fo.w.Flush()
57 |
58 | //print errors
59 | if len(data) <= 0 {
60 | return
61 | }
62 |
63 | now := time.Now().Format(timeFormat)
64 |
65 | errors.ForEach(func(data map[string]int, order []string) {
66 | for _, v := range order {
67 | if data[v] > 1 {
68 | fmt.Fprintf(fo.w, "%s %s (%d)\n", now, v, data[v])
69 | } else {
70 | fmt.Fprintf(fo.w, "%s %s\n", now, v)
71 | }
72 | }
73 | })
74 |
75 | fmt.Fprintln(fo.w, "----------------------------------------------------------------------------------")
76 | }
77 |
78 | func (fo *FileOutput) Start() {}
79 |
80 | func (fo *FileOutput) Stop() {}
81 |
82 | var fileFormatLevelFunc = func(i any) string {
83 | level := strings.ToUpper(i.(string))
84 | return level
85 | }
86 |
--------------------------------------------------------------------------------
/pkg/perf/message.go:
--------------------------------------------------------------------------------
1 | package perf
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "fmt"
7 | "io"
8 | "math/rand"
9 | "os"
10 | "sync"
11 | "sync/atomic"
12 | "text/template"
13 | "time"
14 |
15 | "github.com/akshaykhairmode/wscli/pkg/logger"
16 | "github.com/google/uuid"
17 | )
18 |
19 | type messageGetter interface {
20 | Get(any) ([]byte, func())
21 | GetTemplateString() string
22 | }
23 |
24 | type File struct {
25 | reader *bufio.Reader
26 | f *os.File
27 | dataChan chan []byte
28 | }
29 |
30 | const dataChanSize = 1000
31 |
32 | func NewMessage(fpath string) (messageGetter, error) {
33 |
34 | isFile, size := isFilePath(fpath)
35 | if !isFile {
36 | return NewDefaultMessageGetter(fpath)
37 | }
38 |
39 | f, err := os.Open(fpath)
40 | if err != nil {
41 | return nil, fmt.Errorf("error while opening file : %w", err)
42 | }
43 |
44 | mg := &File{
45 | f: f,
46 | dataChan: make(chan []byte, dataChanSize),
47 | }
48 |
49 | //If file size is less than equals to 10mb we will store in memory.
50 | if size <= 1024*1024*10 {
51 | data, err := io.ReadAll(f)
52 | if err != nil {
53 | return nil, fmt.Errorf("error while reading file : %w", err)
54 | }
55 | mg.reader = bufio.NewReader(bytes.NewReader(data))
56 | logger.Debug().Msgf("Loading File in memory")
57 | } else {
58 | mg.reader = bufio.NewReader(f)
59 | }
60 |
61 | go mg.readWorker()
62 | go mg.logWorker()
63 |
64 | return mg, nil
65 | }
66 |
67 | func (m *File) Get(_ any) ([]byte, func()) {
68 | return <-m.dataChan, func() {}
69 | }
70 |
71 | func (m *File) GetTemplateString() string {
72 | return ""
73 | }
74 |
75 | func (m *File) logWorker() {
76 | for range time.Tick(time.Second) {
77 | if len(m.dataChan) < dataChanSize {
78 | logger.Debug().Msgf("Buffer Length is : %d", len(m.dataChan))
79 | }
80 | }
81 | }
82 |
83 | func (m *File) readWorker() {
84 |
85 | for {
86 | data, err := m.reader.ReadBytes('\n')
87 | if err == nil {
88 | m.dataChan <- bytes.TrimSuffix(data, []byte("\n"))
89 | continue
90 | }
91 |
92 | if err == io.EOF {
93 | if _, err := m.f.Seek(0, 0); err != nil {
94 | logger.Err(err).Msg("error while seeking")
95 | }
96 | m.reader.Reset(m.f)
97 | continue
98 | }
99 |
100 | logger.Err(err).Msg("error while reading the file")
101 | }
102 |
103 | }
104 |
105 | func isFilePath(path string) (bool, int64) {
106 | fileInfo, err := os.Stat(path)
107 | if err != nil {
108 | return false, 0
109 | }
110 |
111 | if fileInfo.IsDir() {
112 | return false, 0
113 | }
114 |
115 | return true, fileInfo.Size()
116 | }
117 |
118 | type DefaultMessageGetter struct {
119 | msg []byte
120 | tmpl *template.Template
121 | pool *sync.Pool
122 | }
123 |
124 | var uniqueSequenceMap = &sync.Map{}
125 |
126 | func NewDefaultMessageGetter(msg string) (messageGetter, error) {
127 |
128 | tmpl := template.New("parse").Funcs(funcMap)
129 | if err := parseTemplate(tmpl, msg); err != nil {
130 | return nil, fmt.Errorf("error while parsing the template : %s : %w", msg, err)
131 | }
132 |
133 | return &DefaultMessageGetter{
134 | msg: []byte(msg),
135 | tmpl: tmpl,
136 | pool: &sync.Pool{
137 | New: func() interface{} {
138 | return bytes.NewBuffer(make([]byte, 0, len(msg)*2))
139 | },
140 | },
141 | }, nil
142 | }
143 |
144 | func (m *DefaultMessageGetter) Get(data any) ([]byte, func()) {
145 |
146 | buf, release := m.getBuffer()
147 |
148 | err := m.tmpl.Execute(buf, data)
149 | if err != nil {
150 | logger.Error().Err(err).Msgf("error while executing the template : %s", m.msg)
151 | return nil, func() {}
152 | }
153 |
154 | return buf.Bytes(), release
155 | }
156 |
157 | func (m *DefaultMessageGetter) getBuffer() (*bytes.Buffer, func()) {
158 | buf := m.pool.Get().(*bytes.Buffer)
159 | return buf, func() {
160 | buf.Reset()
161 | m.pool.Put(buf)
162 | }
163 | }
164 |
165 | func (m *DefaultMessageGetter) GetTemplateString() string {
166 | return string(m.msg)
167 | }
168 |
169 | var funcMap = template.FuncMap{
170 | "RandomNum": randomInt,
171 | "RandomUUID": randomUUID,
172 | "RandomAN": randomAlphaNumeric,
173 | "UniqSeq": getUniqueSequence,
174 | }
175 |
176 | func getUniqueSequence(group string, start ...uint64) uint64 {
177 |
178 | val, _ := uniqueSequenceMap.LoadOrStore(group, getUint64Counter(start...))
179 | tc := val.(*atomic.Uint64)
180 |
181 | newVal := tc.Add(1)
182 |
183 | return newVal - 1
184 | }
185 |
186 | func getUint64Counter(start ...uint64) *atomic.Uint64 {
187 | c := &atomic.Uint64{}
188 | if len(start) <= 0 || start[0] <= 0 {
189 | return c
190 | }
191 |
192 | c.Store(start[0])
193 | return c
194 | }
195 |
196 | const alphaNumericChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
197 |
198 | func randomAlphaNumeric(length ...int) string {
199 | l := 10
200 | if len(length) > 0 {
201 | l = length[0]
202 | }
203 |
204 | b := make([]byte, l)
205 | for i := range b {
206 | b[i] = alphaNumericChars[rand.Intn(len(alphaNumericChars))]
207 | }
208 |
209 | return string(b)
210 | }
211 |
212 | func randomInt(max ...int) int {
213 | if len(max) <= 0 {
214 | return rand.Intn(10000)
215 | }
216 |
217 | return rand.Intn(max[0])
218 | }
219 |
220 | func randomUUID() string {
221 | guid := uuid.New()
222 | return guid.String()
223 | }
224 |
225 | func parseTemplate(tmpl *template.Template, str string) error {
226 |
227 | if str == "" {
228 | return nil
229 | }
230 |
231 | if _, err := tmpl.Parse(str); err != nil {
232 | return fmt.Errorf("error while parsing the template : %w", err)
233 | }
234 |
235 | return nil
236 |
237 | }
238 |
--------------------------------------------------------------------------------
/pkg/perf/message_test.go:
--------------------------------------------------------------------------------
1 | package perf
2 |
3 | import (
4 | "strconv"
5 | "sync"
6 | "testing"
7 | )
8 |
9 | func TestUniqSeq(t *testing.T) {
10 | messageGetter, err := NewDefaultMessageGetter(`{{UniqSeq "test" 10}}`)
11 | if err != nil {
12 | t.Error(err)
13 | return
14 | }
15 |
16 | uniqElems := map[int]int{}
17 | mux := &sync.Mutex{}
18 | wg := &sync.WaitGroup{}
19 |
20 | for i := 0; i < 50000; i++ {
21 | wg.Add(1)
22 | go func() {
23 | defer wg.Done()
24 | val, release := messageGetter.Get(nil)
25 | defer release()
26 |
27 | if err != nil {
28 | t.Error(err)
29 | return
30 | }
31 |
32 | intVal, err := strconv.Atoi(string(val))
33 | if err != nil {
34 | t.Error(err)
35 | return
36 | }
37 |
38 | mux.Lock()
39 | defer mux.Unlock()
40 |
41 | uniqElems[intVal]++
42 | }()
43 | }
44 |
45 | wg.Wait()
46 |
47 | for k, v := range uniqElems {
48 | if v > 1 {
49 | t.Error(k, v)
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/pkg/perf/metrics.go:
--------------------------------------------------------------------------------
1 | package perf
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "fmt"
7 | "io"
8 | "regexp"
9 | "strconv"
10 | "sync"
11 | "time"
12 |
13 | "github.com/akshaykhairmode/wscli/pkg/config"
14 | "github.com/rcrowley/go-metrics"
15 | )
16 |
17 | type Metrics struct {
18 | activeConnections metrics.Counter
19 | droppedConnections metrics.Counter
20 | totalSentMessages metrics.Counter
21 | totalReceivedMessages metrics.Counter
22 | failedMessages metrics.Counter
23 |
24 | connectTime metrics.Timer
25 | messageTime metrics.Timer
26 |
27 | totalConns int64
28 |
29 | errors *errMsg
30 | output Printer
31 |
32 | startTime time.Time
33 | startTimeStr string
34 | }
35 |
36 | type Printer interface {
37 | UpdateTableAndLogs(data []string, errors *errMsg)
38 | Start()
39 | Stop()
40 | }
41 |
42 | type errMsg struct {
43 | data map[string]int
44 | order []string
45 | mux *sync.RWMutex
46 | }
47 |
48 | func (em *errMsg) Add(msg string) {
49 | em.mux.Lock()
50 | defer em.mux.Unlock()
51 |
52 | if _, ok := em.data[msg]; !ok {
53 | em.order = append(em.order, msg)
54 | }
55 |
56 | em.data[msg]++
57 | }
58 |
59 | func (em *errMsg) ForEach(f func(data map[string]int, order []string)) {
60 | em.mux.RLock()
61 | defer em.mux.RUnlock()
62 | f(em.data, em.order)
63 | }
64 |
65 | func NewMetrics(totalConns int64, out string) *Metrics {
66 |
67 | var output Printer
68 |
69 | if out == "" {
70 | output = NewTview()
71 | } else {
72 | output = NewFileOutput(out)
73 | }
74 |
75 | now := time.Now()
76 |
77 | m := &Metrics{
78 | activeConnections: metrics.NewCounter(),
79 | droppedConnections: metrics.NewCounter(),
80 | totalSentMessages: metrics.NewCounter(),
81 | totalReceivedMessages: metrics.NewCounter(),
82 | failedMessages: metrics.NewCounter(),
83 | connectTime: metrics.NewTimer(),
84 | messageTime: metrics.NewTimer(),
85 | totalConns: totalConns,
86 | errors: &errMsg{
87 | data: make(map[string]int),
88 | mux: &sync.RWMutex{},
89 | },
90 | output: output,
91 | startTime: now,
92 | startTimeStr: now.Format(timeFormat),
93 | }
94 |
95 | metrics.MustRegister("active_connections", m.activeConnections)
96 | metrics.MustRegister("dropped_connections", m.droppedConnections)
97 | metrics.MustRegister("total_sent", m.totalSentMessages)
98 | metrics.MustRegister("total_received", m.totalReceivedMessages)
99 | metrics.MustRegister("total_failed", m.failedMessages)
100 | metrics.MustRegister("connection_time", m.connectTime)
101 | metrics.MustRegister("message_time", m.messageTime)
102 |
103 | go m.printMetrics()
104 |
105 | return m
106 | }
107 |
108 | type customBufferedLogger struct {
109 | buf *bytes.Buffer
110 | mux *sync.RWMutex
111 | }
112 |
113 | func (l *customBufferedLogger) Write(p []byte) (n int, err error) {
114 | l.mux.Lock()
115 | defer l.mux.Unlock()
116 | return l.buf.Write(p)
117 | }
118 |
119 | func (l *customBufferedLogger) Read(buf []byte) (int, error) {
120 | l.mux.RLock()
121 | defer l.mux.RUnlock()
122 | return l.buf.Read(buf)
123 | }
124 |
125 | var LogBuffer = &customBufferedLogger{
126 | buf: &bytes.Buffer{},
127 | mux: &sync.RWMutex{},
128 | }
129 |
130 | var re = regexp.MustCompile(`^\d{2}:\d{2}:\d{2}.\d{3} `)
131 |
132 | func stripTimeFromLog(log string) string {
133 | return re.ReplaceAllString(log, "")
134 | }
135 |
136 | func (m *Metrics) printMetrics() {
137 |
138 | go func() {
139 | r := bufio.NewReader(LogBuffer)
140 |
141 | for {
142 | data, _, err := r.ReadLine()
143 | if err == io.EOF {
144 | time.Sleep(200 * time.Millisecond)
145 | continue
146 | }
147 |
148 | if len(data) <= 0 {
149 | continue
150 | }
151 |
152 | str := stripTimeFromLog(string(data))
153 |
154 | m.errors.Add(str)
155 | }
156 |
157 | }()
158 |
159 | go func() {
160 | m.output.UpdateTableAndLogs(m.getTable(headings), m.errors)
161 |
162 | for range time.Tick(config.Flags.PrintOutputInterval) {
163 | m.output.UpdateTableAndLogs(m.getTable(headings), m.errors)
164 | }
165 | }()
166 |
167 | }
168 |
169 | func (m *Metrics) printFinalMetrics() {
170 |
171 | values := m.getTable(headings)
172 | for index, heading := range headings {
173 | fmt.Printf("%s,%s\n", heading, values[index])
174 | }
175 |
176 | }
177 |
178 | const (
179 | timeFormat = "3:04:05 PM"
180 | p95 = 0.95
181 | p99 = 0.99
182 | )
183 |
184 | func (m *Metrics) getTable(heading []string) []string {
185 |
186 | final := []string{}
187 |
188 | connectTime := m.connectTime.Snapshot()
189 | messageTime := m.messageTime.Snapshot()
190 |
191 | for _, val := range heading {
192 |
193 | switch val {
194 | case TotalConnections:
195 | final = append(final, intToString(m.totalConns))
196 | case ActiveConnections:
197 | final = append(final, calculatePercentage(m.activeConnections.Count(), m.totalConns))
198 | case DroppedConnections:
199 | final = append(final, calculatePercentage(m.droppedConnections.Count(), m.totalConns))
200 | case TotalSentMessages:
201 | final = append(final, intToString(m.totalSentMessages.Count()))
202 | case TotalReceivedMessages:
203 | final = append(final, intToString(m.totalReceivedMessages.Count()))
204 | case TotalFailedMessages:
205 | final = append(final, intToString(m.failedMessages.Count()))
206 | case ConnectionMeanTime:
207 | final = append(final, durToString(connectTime.Mean()))
208 | case ConnectionP95Time:
209 | final = append(final, durToString(connectTime.Percentile(p95)))
210 | case ConnectionP99Time:
211 | final = append(final, durToString(connectTime.Percentile(p99)))
212 | case MessageMeanTime:
213 | final = append(final, durToString(messageTime.Mean()))
214 | case MessageP95Time:
215 | final = append(final, durToString(messageTime.Percentile(p95)))
216 | case MessageP99Time:
217 | final = append(final, durToString(messageTime.Percentile(p99)))
218 | case StartTime:
219 | final = append(final, m.startTimeStr)
220 | case Uptime:
221 | final = append(final, time.Since(m.startTime).Round(time.Second).String())
222 | }
223 | }
224 |
225 | return final
226 |
227 | }
228 |
229 | func intToString(i int64) string {
230 | return strconv.Itoa(int(i))
231 | }
232 |
233 | func durToString(f float64) string {
234 | return time.Duration(f).Round(time.Millisecond).String()
235 | }
236 |
237 | func calculatePercentage(value, total int64) string {
238 | if total == 0 {
239 | return "0.00%"
240 | }
241 |
242 | percentage := (float64(value) / float64(total)) * 100
243 |
244 | return fmt.Sprintf("%d (%.2f%%)", value, percentage)
245 |
246 | }
247 |
248 | func (m *Metrics) IncrDroppedConnections() {
249 | m.droppedConnections.Inc(1)
250 | }
251 |
252 | func (m *Metrics) IncrActiveConnections() {
253 | m.activeConnections.Inc(1)
254 | }
255 |
256 | func (m *Metrics) DecrActiveConnections() {
257 | m.activeConnections.Dec(1)
258 | }
259 |
260 | func (m *Metrics) IncrSentMessages() {
261 | m.totalSentMessages.Inc(1)
262 | }
263 |
264 | func (m *Metrics) IncrFailedMessages() {
265 | m.failedMessages.Inc(1)
266 | }
267 |
268 | func (m *Metrics) IncrReceivedMessages() {
269 | m.totalReceivedMessages.Inc(1)
270 | }
271 |
272 | func (m *Metrics) SetAvgConnectTime(dur time.Duration) {
273 | m.connectTime.Update(dur)
274 | }
275 |
276 | func (m *Metrics) SetAvgMessageTime(dur time.Duration) {
277 | m.messageTime.Update(dur)
278 | }
279 |
--------------------------------------------------------------------------------
/pkg/perf/perf.go:
--------------------------------------------------------------------------------
1 | package perf
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/signal"
7 | "sync"
8 | "syscall"
9 | "time"
10 |
11 | "github.com/akshaykhairmode/wscli/pkg/config"
12 | "github.com/akshaykhairmode/wscli/pkg/logger"
13 | "github.com/akshaykhairmode/wscli/pkg/ws"
14 | "github.com/gorilla/websocket"
15 | "gopkg.in/yaml.v3"
16 | )
17 |
18 | type Generator struct {
19 | config config.Perf
20 | metric *Metrics
21 | loadMessage messageGetter
22 | authMessage messageGetter
23 | }
24 |
25 | func New() (*Generator, error) {
26 |
27 | //If config file is passed, overwrite perf config.
28 | if config.Flags.Perf.ConfigPath != "" {
29 | cfgBytes, err := os.ReadFile(config.Flags.Perf.ConfigPath)
30 | if err != nil {
31 | return nil, fmt.Errorf("error while reading the config file : %w", err)
32 | }
33 |
34 | if err := yaml.Unmarshal(cfgBytes, &config.Flags.Perf); err != nil {
35 | return nil, fmt.Errorf("error while unmarshalling the config file : %w", err)
36 | }
37 | }
38 |
39 | if config.Flags.Perf.LogOutFile != "" {
40 | logger.Init(LogBuffer, fileFormatLevelFunc)
41 | } else {
42 | logger.Init(LogBuffer, nil)
43 | }
44 |
45 | if config.Flags.Perf.TotalConns <= 0 {
46 | return nil, fmt.Errorf("total number of connections are required")
47 | }
48 |
49 | lm, err := NewMessage(config.Flags.Perf.LoadMessage)
50 | if err != nil {
51 | return nil, fmt.Errorf("error while getting the load message : %w", err)
52 | }
53 |
54 | am, err := NewMessage(config.Flags.Perf.AuthMessage)
55 | if err != nil {
56 | return nil, fmt.Errorf("error while getting the auth message : %w", err)
57 | }
58 |
59 | logger.Info().Msgf("Config Loaded : %s", config.Flags.Perf)
60 |
61 | return &Generator{
62 | config: config.Flags.Perf,
63 | metric: NewMetrics(int64(config.Flags.Perf.TotalConns), config.Flags.Perf.LogOutFile),
64 | loadMessage: lm,
65 | authMessage: am,
66 | }, nil
67 | }
68 |
69 | func (g *Generator) Run(showTview bool) {
70 |
71 | go func() {
72 | sigs := make(chan os.Signal, 1)
73 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
74 | <-sigs
75 | g.metric.output.Stop()
76 | os.Exit(0)
77 | }()
78 |
79 | logger.Info().Msg("Started the load test")
80 |
81 | wg := &sync.WaitGroup{}
82 |
83 | wg.Add(1)
84 | go func() {
85 | defer wg.Done()
86 |
87 | total := g.config.TotalConns
88 | loop:
89 | for range time.Tick(time.Second) {
90 |
91 | for range g.config.RampUpConnsPerSecond {
92 |
93 | if total <= 0 {
94 | break loop
95 | }
96 |
97 | wg.Add(1)
98 | go g.processConnection(wg)
99 | total--
100 | }
101 |
102 | }
103 | }()
104 |
105 | defer g.metric.printFinalMetrics()
106 |
107 | if showTview {
108 | g.metric.output.Start()
109 | } else {
110 | wg.Wait()
111 |
112 | select {}
113 | }
114 |
115 | }
116 |
117 | func (g *Generator) messgeReceiver(conn *websocket.Conn, wg *sync.WaitGroup, waitChan chan struct{}) {
118 | defer wg.Done()
119 |
120 | defer func() {
121 | waitChan <- struct{}{}
122 | }()
123 |
124 | for {
125 | _, data, err := conn.ReadMessage()
126 | if err != nil {
127 | logger.Err(err).Msg("error while reading the message")
128 | return
129 | }
130 |
131 | if len(data) <= 0 {
132 | continue
133 | }
134 |
135 | g.metric.IncrReceivedMessages()
136 | }
137 | }
138 |
139 | func (g *Generator) processConnection(wg *sync.WaitGroup) {
140 | defer wg.Done()
141 | defer g.metric.IncrDroppedConnections()
142 |
143 | //connect
144 | now := time.Now()
145 | conn, closef, _, err := ws.Connect()
146 | if err != nil {
147 | logger.Error().Err(err).Msg("error while connecting")
148 | return
149 | }
150 | defer g.metric.DecrActiveConnections()
151 | g.metric.IncrActiveConnections()
152 | g.metric.SetAvgConnectTime(time.Since(now))
153 |
154 | defer closef()
155 |
156 | waitChan := make(chan struct{}, 1)
157 | defer func() {
158 | <-waitChan
159 | }()
160 |
161 | //read messages
162 | wg.Add(1)
163 | go g.messgeReceiver(conn, wg, waitChan)
164 |
165 | //Wait for some time before sending auth.
166 | if g.config.WaitBeforeAuth > 0 {
167 | <-time.After(g.config.WaitBeforeAuth)
168 | }
169 |
170 | //send auth message
171 | if g.config.AuthMessage != "" {
172 | func() {
173 | msg, release := g.authMessage.Get(nil)
174 | defer release()
175 |
176 | if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
177 | logger.Error().Err(err).Msg("error while sending the auth message")
178 | return
179 | }
180 | }()
181 |
182 | }
183 |
184 | //wait for auth response.
185 | if g.config.WaitAfterAuth > 0 {
186 | <-time.After(g.config.WaitAfterAuth)
187 | }
188 |
189 | //if load message is empty then we dont send messages
190 | if g.config.LoadMessage == "" {
191 | return
192 | }
193 |
194 | seqCounter := uint64(0)
195 |
196 | lmFunc := func() {
197 | now := time.Now()
198 |
199 | msg, release := g.loadMessage.Get(Sequence{seqCounter})
200 | defer release()
201 |
202 | if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
203 | g.metric.IncrFailedMessages()
204 | logger.Err(err).Msg("error while sending the load message")
205 | return
206 | }
207 |
208 | g.metric.SetAvgMessageTime(time.Since(now))
209 | g.metric.IncrSentMessages()
210 | seqCounter++
211 | }
212 |
213 | //Send Load Mesasge only once when mi is 0.
214 | if g.config.MessageInterval <= 0 {
215 | lmFunc()
216 | return
217 | }
218 |
219 | //send load
220 | for range time.Tick(g.config.MessageInterval) {
221 | lmFunc()
222 | }
223 | }
224 |
225 | type Sequence struct {
226 | Seq uint64
227 | }
228 |
--------------------------------------------------------------------------------
/pkg/perf/tview.go:
--------------------------------------------------------------------------------
1 | package perf
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 |
7 | "github.com/akshaykhairmode/wscli/pkg/logger"
8 | "github.com/gdamore/tcell/v2"
9 | "github.com/rivo/tview"
10 | )
11 |
12 | const (
13 | TotalConnections = "Total"
14 | ActiveConnections = "Active"
15 | DroppedConnections = "Dropped"
16 | TotalSentMessages = "M-Sent"
17 | TotalReceivedMessages = "M-Received"
18 | TotalFailedMessages = "M-Failed"
19 |
20 | ConnectionMeanTime = "C-Mean"
21 | ConnectionP95Time = "C-P95"
22 | ConnectionP99Time = "C-P99"
23 |
24 | MessageMeanTime = "M-Mean"
25 | MessageP95Time = "M-P95"
26 | MessageP99Time = "M-P99"
27 |
28 | StartTime = "StartTime"
29 | Uptime = "Uptime"
30 | )
31 |
32 | var headings = []string{
33 | TotalConnections,
34 | ActiveConnections,
35 | DroppedConnections,
36 | TotalSentMessages,
37 | TotalReceivedMessages,
38 | TotalFailedMessages,
39 |
40 | ConnectionMeanTime,
41 | ConnectionP95Time,
42 | ConnectionP99Time,
43 |
44 | MessageMeanTime,
45 | MessageP95Time,
46 | MessageP99Time,
47 |
48 | StartTime,
49 | Uptime,
50 | }
51 |
52 | var logAutoScroll = true
53 |
54 | func init() {
55 |
56 | }
57 |
58 | type Tview struct {
59 | app *tview.Application
60 | table *tview.Table
61 | logs *tview.TextView
62 | grid *tview.Grid
63 | }
64 |
65 | func NewTview() *Tview {
66 |
67 | tviewApplication := tview.NewApplication()
68 |
69 | tviewTable := tview.NewTable().SetBorders(true)
70 |
71 | tviewLog := tview.NewTextView().
72 | SetDynamicColors(true).
73 | SetScrollable(true).
74 | SetWrap(true)
75 | tviewLog.SetBorder(true)
76 | tviewLog.SetTitle(" wscli - Load Testing ")
77 | tviewLog.SetTitleColor(tcell.ColorBlue)
78 |
79 | tviewGrid := tview.NewGrid().
80 | SetRows(0, 0, 0).
81 | AddItem(tviewTable, 0, 0, 1, 1, 0, 0, false).
82 | AddItem(tviewLog, 1, 0, 2, 1, 0, 0, true).
83 | SetBorders(false)
84 |
85 | tviewLog.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
86 | if event.Key() == tcell.KeyUp || event.Key() == tcell.KeyDown || event.Key() == tcell.KeyPgUp || event.Key() == tcell.KeyPgDn {
87 | logAutoScroll = false
88 | }
89 | return event
90 | })
91 |
92 | for col, h := range headings {
93 | tviewTable.SetCell(0, col, tview.NewTableCell(h).SetTextColor(tcell.ColorDarkKhaki).SetAlign(tview.AlignCenter))
94 | }
95 |
96 | return &Tview{
97 | app: tviewApplication,
98 | table: tviewTable,
99 | logs: tviewLog,
100 | grid: tviewGrid,
101 | }
102 |
103 | }
104 |
105 | func (tv *Tview) Start() {
106 | if err := tv.app.SetRoot(tv.grid, true).Run(); err != nil {
107 | logger.Err(err).Send()
108 | }
109 | }
110 |
111 | func (tv *Tview) Stop() {
112 | tv.app.Stop()
113 | }
114 |
115 | func (tv *Tview) UpdateTableAndLogs(data []string, errors *errMsg) {
116 |
117 | tv.app.QueueUpdateDraw(func() {
118 | updateTable(tv.table, data)
119 | builder := strings.Builder{}
120 | errors.ForEach(func(data map[string]int, order []string) {
121 | for _, v := range order {
122 | if data[v] > 1 {
123 | builder.WriteString(fmt.Sprintf("%s [grey](%d)[white]\n", v, data[v]))
124 | } else {
125 | builder.WriteString(fmt.Sprintf("%s\n", v))
126 | }
127 | }
128 | })
129 |
130 | tv.logs.SetText(builder.String())
131 |
132 | if logAutoScroll {
133 | tv.logs.ScrollToEnd().ScrollToHighlight()
134 | }
135 | })
136 |
137 | }
138 |
139 | func updateTable(table *tview.Table, values []string) {
140 | for col, val := range values {
141 | cell := tview.NewTableCell(val).SetAlign(tview.AlignCenter)
142 | if col == 2 {
143 | cell.SetTextColor(tcell.ColorRed)
144 | } else {
145 | cell.SetTextColor(tcell.ColorGreen)
146 | }
147 | table.SetCell(1, col, cell)
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/pkg/processer/processor.go:
--------------------------------------------------------------------------------
1 | package processer
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "io"
7 | "log"
8 | "os"
9 | "os/signal"
10 | "strconv"
11 | "strings"
12 | "syscall"
13 | "time"
14 |
15 | "github.com/akshaykhairmode/wscli/pkg/config"
16 | "github.com/akshaykhairmode/wscli/pkg/logger"
17 | "github.com/akshaykhairmode/wscli/pkg/terminal"
18 | "github.com/akshaykhairmode/wscli/pkg/ws"
19 |
20 | "github.com/gorilla/websocket"
21 | )
22 |
23 | type Interactive struct {
24 | conn *websocket.Conn
25 | term *terminal.Term
26 | }
27 |
28 | func New(conn *websocket.Conn, term *terminal.Term) *Interactive {
29 | return &Interactive{
30 | conn: conn,
31 | term: term,
32 | }
33 | }
34 |
35 | func ProcessAsCmd(conn *websocket.Conn) {
36 | for _, cmd := range config.Flags.Execute {
37 | ws.WriteToServer(conn, websocket.TextMessage, []byte(cmd))
38 | }
39 |
40 | defer func() {
41 | <-time.After(config.Flags.Wait)
42 | }()
43 |
44 | if config.Flags.IsSTDin {
45 | go catchSignals(conn, nil)
46 | scanner := bufio.NewScanner(os.Stdin)
47 | for scanner.Scan() {
48 | ws.WriteToServer(conn, websocket.TextMessage, scanner.Bytes())
49 | }
50 | }
51 | }
52 |
53 | func (i *Interactive) Process() {
54 |
55 | for _, cmd := range config.Flags.Execute {
56 | ws.WriteToServer(i.conn, websocket.TextMessage, []byte(cmd))
57 | }
58 |
59 | i.term.AppendPrompt(fmt.Sprintf("(%s)»", truncateString(config.Flags.ConnectURL, 25)))
60 |
61 | i.term.OnMessage(func(line string) {
62 | switch {
63 | case shouldProcessCommand(line, "/flags"):
64 | log.Println(config.Flags.String())
65 | case shouldProcessCommand(line, "/ping"):
66 | getPingPongHandler(i.conn, line, websocket.PingMessage)()
67 | case shouldProcessCommand(line, "/pong"):
68 | getPingPongHandler(i.conn, line, websocket.PongMessage)()
69 | case shouldProcessCommand(line, "/close"):
70 | closeHandler(i.conn, line)
71 | case shouldProcessCommand(line, "/bfile"):
72 | sendBinaryFile(i.conn, line)
73 | default:
74 | ws.WriteToServer(i.conn, websocket.TextMessage, []byte(line))
75 | }
76 | })
77 |
78 | }
79 |
80 | func sendBinaryFile(conn *websocket.Conn, line string) {
81 | filePath := strings.TrimSpace(line[6:])
82 | if filePath == "" {
83 | log.Println("filepath is empty")
84 | return
85 | }
86 |
87 | f, err := os.Open(filePath)
88 | if err != nil {
89 | log.Printf("file open err : %s", err)
90 | return
91 | }
92 |
93 | fi, err := f.Stat()
94 | if err != nil {
95 | log.Printf("file stat err : %s", err)
96 | return
97 | }
98 |
99 | if fi.Size() > 50*1024*1024 {
100 | log.Println("file size is greater than 50mb")
101 | return
102 | }
103 |
104 | fileData, err := io.ReadAll(f)
105 | if err != nil {
106 | log.Printf("readall error : %s", err)
107 | return
108 | }
109 |
110 | ws.WriteToServer(conn, websocket.BinaryMessage, fileData)
111 | log.Println("file sent successfully")
112 |
113 | }
114 |
115 | func shouldProcessCommand(line, prefix string) bool {
116 | if config.Flags.IsSlash && strings.HasPrefix(line, prefix) {
117 | return true
118 | }
119 |
120 | return false
121 | }
122 |
123 | func truncateString(s string, n int) string {
124 | r := []rune(s) // Convert to rune slice to handle Unicode correctly
125 | if len(r) > n {
126 | return string(r[:n]) + "..."
127 | }
128 | return s
129 | }
130 |
131 | func closeHandler(conn *websocket.Conn, line string) {
132 | str := strings.TrimSpace(line[6:])
133 | if len(str) > 0 {
134 | spl := strings.Split(str, " ")
135 | if len(spl) < 2 {
136 | log.Println("invalid close message, close message must have code and reason")
137 | return
138 | }
139 |
140 | closeCode, err := strconv.Atoi(spl[0])
141 | if err != nil {
142 | log.Println("invalid close code, must be a number")
143 | return
144 | }
145 |
146 | reason := strings.TrimSpace(strings.Join(spl[1:], " "))
147 |
148 | if err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(closeCode, reason), time.Now().Add(3*time.Second)); err != nil {
149 | logger.Err(err).Msg("write close error")
150 | }
151 | }
152 | }
153 |
154 | func getPingPongHandler(conn *websocket.Conn, line string, mt int) func() {
155 | return func() {
156 | str := strings.TrimSpace(line[5:])
157 | if err := conn.WriteControl(mt, []byte(str), time.Now().Add(3*time.Second)); err != nil {
158 | log.Println(err)
159 | }
160 | }
161 | }
162 |
163 | func catchSignals(conn *websocket.Conn, term *terminal.Term) {
164 | sigs := make(chan os.Signal, 2)
165 |
166 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
167 |
168 | logger.Debug().Msgf("received signal %s", <-sigs)
169 |
170 | if conn != nil {
171 | if err := conn.Close(); err != nil {
172 | logger.Debug().Err(err).Msg("error while closing connection")
173 | }
174 | }
175 |
176 | if term != nil {
177 | term.Close()
178 | }
179 |
180 | time.Sleep(300 * time.Millisecond)
181 | os.Exit(0)
182 |
183 | }
184 |
--------------------------------------------------------------------------------
/pkg/terminal/terminal.go:
--------------------------------------------------------------------------------
1 | package terminal
2 |
3 | import (
4 | "io"
5 | "log"
6 | "strings"
7 | "sync"
8 |
9 | "github.com/akshaykhairmode/wscli/pkg/config"
10 | "github.com/akshaykhairmode/wscli/pkg/logger"
11 | "github.com/akshaykhairmode/wscli/pkg/ws"
12 | "github.com/chzyer/readline"
13 | )
14 |
15 | type Term struct {
16 | rl *readline.Instance
17 | onMessage func(line string)
18 | }
19 |
20 | type CloseFunc func() error
21 |
22 | func New() (*Term, CloseFunc, *sync.WaitGroup) {
23 |
24 | if config.Flags.IsSTDin {
25 | return &Term{}, func() error { return nil }, &sync.WaitGroup{}
26 | }
27 |
28 | rl, err := readline.NewEx(getDefaultConfig())
29 | if err != nil {
30 | logger.Fatal().Err(err).Msg("error while creating readline object")
31 | }
32 |
33 | if !config.Flags.IsSTDin {
34 | rl.CaptureExitSignal()
35 | }
36 |
37 | wg := &sync.WaitGroup{}
38 |
39 | term := &Term{rl: rl}
40 |
41 | log.SetOutput(term.GetOutLoc())
42 | log.SetFlags(0)
43 |
44 | log.Println(ws.GreenColor("Connected"))
45 |
46 | return term, rl.Close, wg
47 | }
48 |
49 | func (t *Term) Close() {
50 | if err := t.rl.Close(); err != nil {
51 | logger.Debug().Err(err).Msg("error while closing terminal")
52 | }
53 | }
54 |
55 | func (t *Term) AppendPrompt(prompt string) {
56 | t.rl.SetPrompt(getPrompt(prompt))
57 | t.rl.Refresh()
58 | }
59 |
60 | func (t *Term) GetOutLoc() io.Writer {
61 | return t.rl.Stderr()
62 | }
63 |
64 | func (t *Term) Reader(wg *sync.WaitGroup) {
65 |
66 | for {
67 | line, err := t.rl.Readline()
68 | if err == readline.ErrInterrupt {
69 | if len(line) == 0 {
70 | return
71 | } else {
72 | continue
73 | }
74 | }
75 | if err != nil {
76 | logger.Debug().Err(err).Msg("error while doing next line in terminal")
77 | return
78 | }
79 |
80 | line = strings.TrimSpace(line)
81 | if len(line) == 0 {
82 | continue
83 | }
84 |
85 | if line == "/exit" || line == "exit" {
86 | return
87 | }
88 |
89 | if t.onMessage != nil {
90 | t.onMessage(line)
91 | }
92 |
93 | }
94 | }
95 |
96 | func (t *Term) OnMessage(f func(line string)) {
97 | t.onMessage = f
98 | }
99 |
--------------------------------------------------------------------------------
/pkg/terminal/util.go:
--------------------------------------------------------------------------------
1 | package terminal
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "path/filepath"
7 | "runtime"
8 |
9 | "github.com/akshaykhairmode/wscli/pkg/config"
10 | "github.com/akshaykhairmode/wscli/pkg/logger"
11 | "github.com/chzyer/readline"
12 | )
13 |
14 | var completer = readline.NewPrefixCompleter(
15 | readline.PcItem("/connect"),
16 | readline.PcItem("/exit"),
17 | readline.PcItem("/ping"),
18 | readline.PcItem("/pong"),
19 | readline.PcItem("/wait"),
20 | readline.PcItem("/help"),
21 | readline.PcItem("/flags"),
22 | readline.PcItem("/print"),
23 | )
24 |
25 | func getDefaultConfig() *readline.Config {
26 | return &readline.Config{
27 | Prompt: getPrompt("» "),
28 | AutoComplete: completer,
29 | HistoryFile: getHistoryFilePath("wscli"),
30 | InterruptPrompt: "^C",
31 | EOFPrompt: "exit",
32 |
33 | HistorySearchFold: true,
34 | }
35 | }
36 |
37 | func getPrompt(str string) string {
38 | if config.Flags.NoColor {
39 | return str
40 | }
41 |
42 | return fmt.Sprintf("\033[31m%s\033[0m ", str)
43 | }
44 |
45 | func getHistoryFilePath(appName string) string {
46 |
47 | fallback := ".readline.history"
48 |
49 | homeDir, err := os.UserHomeDir()
50 | if err != nil {
51 | logger.Debug().Err(err).Msg("error while getting homedir")
52 | return fallback
53 | }
54 |
55 | var historyPath string
56 | switch runtime.GOOS {
57 | case "linux", "darwin":
58 | configDir := filepath.Join(homeDir, ".config", appName)
59 | err := os.MkdirAll(configDir, 0700)
60 | if err != nil {
61 | logger.Debug().Err(err).Msg("error while creating directory in linux,darwin os")
62 | return fallback
63 | }
64 | historyPath = filepath.Join(configDir, "history")
65 | case "windows":
66 | appData := os.Getenv("AppData")
67 | configDir := filepath.Join(appData, appName)
68 | err := os.MkdirAll(configDir, 0700)
69 | if err != nil {
70 | logger.Debug().Err(err).Msg("error while creating directory in windows os")
71 | return fallback
72 | }
73 | historyPath = filepath.Join(configDir, "history")
74 | default:
75 | historyPath = filepath.Join(homeDir, "."+appName+"_history")
76 | }
77 |
78 | logger.Debug().Msgf("History Path is %s", historyPath)
79 |
80 | return historyPath
81 | }
82 |
--------------------------------------------------------------------------------
/pkg/ws/ws.go:
--------------------------------------------------------------------------------
1 | package ws
2 |
3 | import (
4 | "bytes"
5 | "compress/gzip"
6 | "crypto/aes"
7 | "crypto/cipher"
8 | "crypto/des"
9 | "crypto/tls"
10 | "crypto/x509"
11 | "encoding/base64"
12 | "encoding/hex"
13 | "encoding/json"
14 | "encoding/pem"
15 | "errors"
16 | "fmt"
17 | "io"
18 | "log"
19 | "net"
20 | "net/http"
21 | "net/url"
22 | "os"
23 | "strings"
24 | "time"
25 |
26 | "github.com/akshaykhairmode/wscli/pkg/config"
27 | "github.com/akshaykhairmode/wscli/pkg/global"
28 | "github.com/akshaykhairmode/wscli/pkg/logger"
29 | "github.com/fatih/color"
30 | "github.com/gorilla/websocket"
31 | )
32 |
33 | type CloseFunc func()
34 |
35 | type ReaderFunc func(*websocket.Conn)
36 |
37 | func Connect() (*websocket.Conn, CloseFunc, ReaderFunc, error) {
38 |
39 | closeFunc := func() {}
40 | rFunc := ReaderFunc(func(*websocket.Conn) {})
41 |
42 | if config.Flags.ConnectURL == "" {
43 | return nil, closeFunc, rFunc, fmt.Errorf("connect url is empty")
44 | }
45 |
46 | u, err := url.Parse(config.Flags.ConnectURL)
47 | if err != nil {
48 | return nil, closeFunc, rFunc, fmt.Errorf("error while passing the url : %w", err)
49 | }
50 |
51 | headers := http.Header{}
52 | for _, h := range config.Flags.Headers {
53 | headSpl := strings.Split(h, ":")
54 | if len(headSpl) != 2 {
55 | return nil, closeFunc, rFunc, fmt.Errorf("invalid header : %s", h)
56 | }
57 | headers.Set(headSpl[0], headSpl[1])
58 | }
59 |
60 | if config.Flags.Origin != "" {
61 | headers.Set("Origin", config.Flags.Origin)
62 | }
63 |
64 | if config.Flags.Auth != "" {
65 | headers.Set("Authorization", BasicAuth(config.Flags.Auth))
66 | }
67 |
68 | dialer := websocket.Dialer{
69 | Subprotocols: config.Flags.SubProtocol,
70 | TLSClientConfig: GetTLSConfig(),
71 | }
72 |
73 | if config.Flags.Proxy != "" {
74 | proxyURLParsed, err := url.Parse(config.Flags.Proxy)
75 | if err != nil {
76 | return nil, closeFunc, rFunc, fmt.Errorf("error while parsing the proxy url : %w", err)
77 | }
78 | dialer.Proxy = http.ProxyURL(proxyURLParsed)
79 | }
80 |
81 | c, resp, err := dialer.Dial(u.String(), headers)
82 | if err != nil {
83 | return nil, closeFunc, rFunc, fmt.Errorf("dial error : %w", err)
84 | }
85 |
86 | if config.Flags.ShouldShowResponseHeaders {
87 | for k, v := range resp.Header {
88 | log.Println(k, v)
89 | }
90 | }
91 |
92 | closeFunc = func() {
93 | if err := c.Close(); err != nil {
94 | logger.Debug().Err(err).Msg("error while closing the connection")
95 | }
96 | }
97 |
98 | go PingWorker(c)
99 |
100 | return c, closeFunc, readMessages, nil
101 | }
102 |
103 | func PingWorker(c *websocket.Conn) {
104 | for range time.Tick(config.Flags.PingInterval) {
105 | err := c.WriteControl(websocket.PingMessage, nil, time.Now().Add(3*time.Second))
106 | if err != nil {
107 | if err.Error() == "websocket: close sent" {
108 | return
109 | }
110 | logger.Debug().Err(err).Msg("error while pinging")
111 | }
112 | }
113 | }
114 |
115 | func BasicAuth(auth string) string {
116 | return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
117 | }
118 |
119 | var BlueColor = color.New(color.FgBlue).SprintfFunc()
120 | var GreenColor = color.New(color.FgGreen).SprintfFunc()
121 |
122 | func readMessages(conn *websocket.Conn) {
123 |
124 | fn := func(what string) func(appData string) error {
125 | return func(appData string) error {
126 | if config.Flags.ShowPingPong {
127 | log.Println(BlueColor("received %s (data: %s)", what, appData))
128 | }
129 | return nil
130 | }
131 | }
132 |
133 | defer func() {
134 | logger.Debug().Msg("enabling global stop application flag")
135 | global.Stop()
136 | }()
137 |
138 | conn.SetPingHandler(fn("ping"))
139 | conn.SetPongHandler(fn("pong"))
140 |
141 | for {
142 | mt, message, err := conn.ReadMessage()
143 | if err != nil {
144 | if errors.Is(err, net.ErrClosed) {
145 | return
146 | }
147 |
148 | log.Println(err.Error())
149 | return
150 | }
151 |
152 | switch mt {
153 | case websocket.TextMessage:
154 | log.Println(formatMessage(message))
155 | case websocket.BinaryMessage:
156 | if config.Flags.IsGzipResponse {
157 | gzBytes, err := unzipGzipBytes(message)
158 | if err != nil {
159 | logger.Err(err).Msg("error while unzipping bytes")
160 | } else {
161 | log.Println(gzBytes)
162 | }
163 | } else {
164 | log.Println(hex.EncodeToString(message))
165 | }
166 | case websocket.CloseMessage:
167 | log.Println("received close message", message)
168 | return
169 | }
170 |
171 | }
172 |
173 | }
174 |
175 | func unzipGzipBytes(gzipBytes []byte) (string, error) {
176 | reader := bytes.NewReader(gzipBytes)
177 | gzipReader, err := gzip.NewReader(reader)
178 | if err != nil {
179 | return "", fmt.Errorf("failed to create gzip reader: %w", err)
180 | }
181 | defer gzipReader.Close()
182 |
183 | unzippedBytes, err := io.ReadAll(gzipReader)
184 | if err != nil {
185 | return "", fmt.Errorf("failed to read unzipped data: %w", err)
186 | }
187 |
188 | return string(unzippedBytes), nil
189 | }
190 |
191 | func formatMessage(message []byte) string {
192 |
193 | if !config.Flags.IsJSONPrettyPrint {
194 | return GreenColor("« %s", message)
195 | }
196 |
197 | m := map[string]any{}
198 | if err := json.Unmarshal(message, &m); err != nil {
199 | logger.Debug().Err(err).Msg("UNMARSHAL ERR")
200 | return GreenColor("« %s", message)
201 | }
202 |
203 | jenc, err := json.MarshalIndent(m, "", " ")
204 | if err != nil {
205 | logger.Debug().Err(err).Msg("MARSHALINDENT ERR")
206 | return GreenColor("« %s", message)
207 | }
208 |
209 | return GreenColor("%s", jenc)
210 | }
211 |
212 | func WriteToServer(conn *websocket.Conn, mt int, message []byte) {
213 |
214 | if conn == nil {
215 | logger.Error().Msg("Connection is nil")
216 | return
217 | }
218 |
219 | if !config.Flags.IsBinary {
220 | if err := conn.WriteMessage(mt, message); err != nil {
221 | logger.Err(err).Msg("write error")
222 | }
223 | return
224 | }
225 |
226 | dec, err := hex.DecodeString(string(message))
227 | if err != nil {
228 | logger.Err(err).Msg("error while doing decode string")
229 | return
230 | }
231 | if err := conn.WriteMessage(websocket.BinaryMessage, dec); err != nil {
232 | logger.Err(err).Msg("write error")
233 | }
234 |
235 | }
236 |
237 | func GetTLSConfig() *tls.Config {
238 |
239 | if config.Flags.NoCertificateCheck {
240 | return &tls.Config{
241 | InsecureSkipVerify: true,
242 | }
243 | }
244 |
245 | caCertPool := processCACert(config.Flags.TLS.CA)
246 |
247 | certificates, err := processCert(config.Flags.TLS.Cert, config.Flags.TLS.Key, config.Flags.TLS.Passphrase)
248 | if err != nil {
249 | logger.Fatal().Err(err).Msg("error while processing client certificate")
250 | return nil
251 | }
252 |
253 | return &tls.Config{
254 | RootCAs: caCertPool,
255 | Certificates: certificates,
256 | }
257 | }
258 |
259 | func processCert(certPath, keyPath, passphrase string) ([]tls.Certificate, error) {
260 |
261 | if certPath == "" && keyPath == "" {
262 | return nil, nil
263 | }
264 |
265 | if certPath != "" && keyPath == "" {
266 | return nil, fmt.Errorf("key is required if certificate is provided")
267 | }
268 |
269 | cert, err := os.ReadFile(certPath)
270 | if err != nil {
271 | return nil, fmt.Errorf("error while reading certificate : %w", err)
272 | }
273 |
274 | key, err := os.ReadFile(keyPath)
275 | if err != nil {
276 | return nil, fmt.Errorf("error while reading key : %w", err)
277 | }
278 |
279 | dkey, err := decryptPrivateKey(key, []byte(passphrase))
280 | if err != nil {
281 | return nil, fmt.Errorf("error while decrypting private key with passphrase : %w", err)
282 | }
283 |
284 | clientCert, err := tls.X509KeyPair(cert, dkey)
285 | if err != nil {
286 | return nil, fmt.Errorf("error while creating client certificate : %w", err)
287 | }
288 |
289 | return []tls.Certificate{clientCert}, nil
290 |
291 | }
292 |
293 | func processCACert(caCertPath string) *x509.CertPool {
294 |
295 | if caCertPath == "" {
296 | return nil
297 | }
298 |
299 | caCert, err := os.ReadFile(caCertPath)
300 | if err != nil {
301 | logger.Fatal().Err(err).Msg("error while reading CA certificate")
302 | return nil
303 | }
304 | caCertPool := x509.NewCertPool()
305 |
306 | ok := caCertPool.AppendCertsFromPEM(caCert)
307 | if !ok {
308 | logger.Fatal().Err(err).Msg("error while parsing CA certificate")
309 | return nil
310 | }
311 |
312 | return caCertPool
313 |
314 | }
315 |
316 | func decryptPrivateKey(keyPEM []byte, passphrase []byte) ([]byte, error) {
317 | block, _ := pem.Decode(keyPEM)
318 | if block == nil {
319 | return nil, fmt.Errorf("failed to decode PEM block")
320 | }
321 |
322 | if block.Type == "RSA PRIVATE KEY" || block.Type == "PRIVATE KEY" {
323 | // Unencrypted RSA private key
324 | return block.Bytes, nil
325 | } else if block.Type == "ENCRYPTED PRIVATE KEY" {
326 |
327 | if len(block.Bytes) < 8 {
328 | return nil, fmt.Errorf("invalid encrypted private key")
329 | }
330 | if len(passphrase) == 0 {
331 | return nil, fmt.Errorf("passphrase required")
332 | }
333 | if len(passphrase) > 24 {
334 | passphrase = passphrase[:24]
335 | }
336 |
337 | c, err := des.NewTripleDESCipher(passphrase)
338 | if err != nil {
339 | return nil, err
340 | }
341 | iv := block.Bytes[:8]
342 | mode := cipher.NewCBCDecrypter(c, iv)
343 | plaintext := make([]byte, len(block.Bytes)-8)
344 | mode.CryptBlocks(plaintext, block.Bytes[8:])
345 | return plaintext, nil
346 |
347 | } else if block.Type == "AES-256-CBC ENCRYPTED PRIVATE KEY" || block.Type == "AES-128-CBC ENCRYPTED PRIVATE KEY" {
348 | // Modern encrypted private key format (AES)
349 | block, _ := pem.Decode(keyPEM) // Decode again to get the correct block after checking type
350 |
351 | if block == nil {
352 | return nil, fmt.Errorf("failed to decode PEM block")
353 | }
354 |
355 | if len(block.Bytes) < 16 {
356 | return nil, fmt.Errorf("invalid AES encrypted private key")
357 | }
358 |
359 | if len(passphrase) == 0 {
360 | return nil, fmt.Errorf("passphrase required")
361 | }
362 |
363 | c, err := aes.NewCipher(passphrase) // AES key size depends on your encryption (16, 24, or 32 bytes)
364 | if err != nil {
365 | return nil, err
366 | }
367 |
368 | iv := block.Bytes[:16] // Initialization vector
369 | mode := cipher.NewCBCDecrypter(c, iv)
370 | plaintext := make([]byte, len(block.Bytes)-16)
371 | mode.CryptBlocks(plaintext, block.Bytes[16:])
372 | return plaintext, nil
373 | } else {
374 | return nil, fmt.Errorf("unsupported private key type: %s", block.Type)
375 | }
376 | }
377 |
--------------------------------------------------------------------------------
/server/main.go:
--------------------------------------------------------------------------------
1 | // nolint
2 | package main
3 |
4 | import (
5 | "bytes"
6 | "compress/gzip"
7 | "context"
8 | "fmt"
9 | "log"
10 | "net/http"
11 | "os"
12 | "os/signal"
13 | "time"
14 |
15 | "github.com/lesismal/nbio/nbhttp"
16 | "github.com/lesismal/nbio/nbhttp/websocket"
17 | )
18 |
19 | var (
20 | upgrader = newUpgrader()
21 | )
22 |
23 | func newUpgrader() *websocket.Upgrader {
24 | u := websocket.NewUpgrader()
25 | u.SetPingHandler(func(c *websocket.Conn, s string) {
26 | // log.Println("Received Ping:", s)
27 | c.WriteMessage(websocket.PongMessage, []byte(s))
28 | })
29 |
30 | u.SetPongHandler(func(c *websocket.Conn, s string) {
31 | // log.Println("Received Pong:", s)
32 | c.WriteMessage(websocket.PingMessage, []byte(s))
33 | })
34 |
35 | u.OnOpen(func(c *websocket.Conn) {
36 | // echo
37 | // fmt.Println("OnOpen:", c.RemoteAddr().String())
38 |
39 | // if rand.IntN(10) > 5 {
40 | // go func() {
41 | // time.Sleep(5 * time.Second)
42 | // c.WriteClose(3008, "closing after 5s")
43 | // }()
44 | // }
45 |
46 | })
47 | u.OnMessage(func(c *websocket.Conn, messageType websocket.MessageType, data []byte) {
48 |
49 | if string(data) == "zip" {
50 | zipData, err := zipStringToGzipBytes("hello, this is zipped data")
51 | if err != nil {
52 | log.Println(err)
53 | return
54 | }
55 | c.WriteMessage(websocket.BinaryMessage, zipData)
56 | }
57 |
58 | log.Println(messageType, string(data))
59 | // echo
60 | // fmt.Println("OnMessage:", messageType, string(data))
61 | c.WriteMessage(messageType, data)
62 | })
63 | u.OnClose(func(c *websocket.Conn, err error) {
64 | fmt.Println("OnClose:", c.RemoteAddr().String(), err)
65 | })
66 |
67 | return u
68 | }
69 |
70 | func zipStringToGzipBytes(input string) ([]byte, error) {
71 | var b bytes.Buffer
72 | gz := gzip.NewWriter(&b)
73 | _, err := gz.Write([]byte(input))
74 | if err != nil {
75 | return nil, fmt.Errorf("failed to write gzip data: %w", err)
76 | }
77 | err = gz.Close()
78 | if err != nil {
79 | return nil, fmt.Errorf("failed to close gzip writer: %w", err)
80 | }
81 | return b.Bytes(), nil
82 | }
83 |
84 | func onWebsocket(w http.ResponseWriter, r *http.Request) {
85 | _, err := upgrader.Upgrade(w, r, nil)
86 | if err != nil {
87 | panic(err)
88 | }
89 | // fmt.Println("Upgraded:", conn.RemoteAddr().String())
90 | }
91 |
92 | func main() {
93 | mux := &http.ServeMux{}
94 | mux.HandleFunc("/ws", onWebsocket)
95 | engine := nbhttp.NewEngine(nbhttp.Config{
96 | Network: "tcp",
97 | Addrs: []string{"localhost:8080"},
98 | MaxLoad: 1000000,
99 | ReleaseWebsocketPayload: true,
100 | Handler: mux,
101 | })
102 |
103 | err := engine.Start()
104 | if err != nil {
105 | fmt.Printf("nbio.Start failed: %v\n", err)
106 | return
107 | }
108 |
109 | interrupt := make(chan os.Signal, 1)
110 | signal.Notify(interrupt, os.Interrupt)
111 | <-interrupt
112 |
113 | ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
114 | defer cancel()
115 | engine.Shutdown(ctx)
116 | }
117 |
--------------------------------------------------------------------------------
/tag.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | tag_name="$1"
4 |
5 | if [ -z "$tag_name" ]; then
6 | echo "Error: Tag name is required."
7 | exit 1
8 | fi
9 |
10 | # Check if the tag already exists locally
11 | if git tag --list | grep -q "^$tag_name$"; then
12 | echo "Error: Tag '$tag_name' already exists locally."
13 | exit 1
14 | fi
15 |
16 | # Check if the tag already exists remotely
17 | if git ls-remote --tags origin | grep -q "refs/tags/$tag_name$"; then
18 | echo "Error: Tag '$tag_name' already exists remotely."
19 | exit 1
20 | fi
21 |
22 | # Create the tag with a message
23 | if ! git tag -a "$tag_name" -m "Release $tag_name"; then
24 | echo "Error: Failed to create tag '$tag_name'."
25 | exit 1
26 | fi
27 |
28 | # Push the tag to the remote repository
29 | if ! git push origin "$tag_name"; then
30 | echo "Error: Failed to push tag '$tag_name' to origin."
31 | exit 1
32 | fi
33 |
34 | echo "Tag '$tag_name' created and pushed successfully."
35 | exit 0
36 |
--------------------------------------------------------------------------------
/test.txt:
--------------------------------------------------------------------------------
1 | hello1
2 | hello2
3 | hello3
4 |
--------------------------------------------------------------------------------