aboutsummaryrefslogtreecommitdiff
path: root/lib/websocket/client.go
AgeCommit message (Collapse)Author
2025-02-04all: remove the nolint tagsShulhan
The "nolint" tag is used to ignore lines from being processed by golangci-lint. Since we are not using golangci-lint anymore, now and in the future, those lines can be removed.
2024-03-05all: comply with linter recommendations #3Shulhan
For HTTP server that use TLS, set the minimum TLS version and ReadHeaderTimeout to mitigate slowloris attack. For HTTP client or server that parameterize the use of InsecureSkipVerify, annotate the line with "nolint:gosec" to allow the code pass the check. Library that still use sha1, in example in DKIM and TOTP, skip the warnings by annotating the line with "nolint:gosec". A pointer variable now allocated their address before assigning its value. Any error that returned now wrapped using "%w". Also, replace error checking using [errors.Is] or [errors.As] instead of using equal or not-equal operators. In "lib/http", replace any usage of "math/rand" with "crypto/rand". Any call of [math/big.Rat.SetString] now annotated with "nolint:gosec" since its false positive, the issue has been fixed in Go >= 1.17.7. Any switch case that does not cover the rest of the possible values now handled by adding the cases or by replacing the "default" case with the rest of values.
2024-03-05all: comply with linter recommendations #2Shulhan
HTTP request now implicitly create request with context. Any false positive related to not closing HTTP response body has been annotated with "nolint:bodyclose". In the example code, use consistent "// Output:" comment format, by prefixing with single space. Any comment on code now also prefixing with single space. An error returned without variables now use [errors.New] instead of [fmt.Errorf]. Any error returned using [fmt.Errorf] now wrapped using "%w" instead of "%s". Also, replace error checking using [errors.Is] or [errors.As], instead of using equal/not-equal operator. Any statement like "x = x OP y" now replaced with "x OP= y". Also, swap statement is simplified using "x, y = y, x". Any switch statement with single case now replaced with if-condition. Any call to defer on function or program that call [os.Exit], now replaced by calling the deferred function directly. Any if-else condition now replaced with switch statement, if possible.
2024-03-02all: move the repository to "git.sr.ht/~shulhan/pakakeh.go"Shulhan
There are several reasons that why we move from github.com. First, related to the name of package. We accidentally name the package with "share" a common word in English that does not reflect the content of repository. By moving to other repository, we can rename it to better and unique name, in this "pakakeh.go". Pakakeh is Minang word for tools, and ".go" suffix indicate that the repository related to Go programming language. Second, supporting open source. The new repository is hosted under sourcehut.org, the founder is known to support open source, and all their services are licensed under AGPL, unlike GitHub that are closed sources. Third, regarding GitHub CoPilot. The GitHub Terms of Service [1], allow any public content that are hosted there granted them to parse the content. On one side, GitHub helps and flourish the open source, but on another side have an issues regarding scraping the copyleft license [2]. [1]: https://docs.github.com/en/site-policy/github-terms/github-terms-of-service#4-license-grant-to-us [2]: https://githubcopilotinvestigation.com
2023-12-13all: fix linter warnings reported by reviveShulhan
There are some reports that I disagree with revive, in example, code should not declare the type after variables. In my opinion, on some cases, declaring the type make the code more readable and explicit. Since I did not want to add new configuration file, we changes it and follow revive for now.
2023-09-11lib/websocket: suppress unused parameter using "_"Shulhan
This fix some linter warnings on dummy methods and handlers.
2023-07-01lib/websocket: reformat comments and documentationShulhan
2023-07-01lib/websocket: prefix the error with function or method namesShulhan
Adding prefix provide better way to locate and debug the error in the future.
2023-06-18lib/websocket: call Quit when handshake contains close or invalid frameShulhan
If the HTTP handshake response contains trailing frame, handle it directly. If the frame is invalid or control close operation, call Quit directly to trigger the HandleQuit if its defined by user.
2023-05-20all: remove any usage of debug.Value in all packagesShulhan
Using global debug value for all packages turns out is not a good idea.
2022-10-10lib/websocket: cleanup the channel gracefulClose during CloseShulhan
When calling Close, we initialize the internal channel gracefulClose so the client can check the close response from server on another goroutine serve() and signal back to Close to continue the closing process. This channel is never closed and nil-ed again after Close which may cause resource leaks. While at it, use sendClose to minimize duplicate code.
2022-10-10lib/websocket: replace handleInvalidData and BadRequest with sendCloseShulhan
Both of those functions actually call send control CLOSE frame and not exported. So, instead of duplicating it, we replace it with sendClose.
2022-10-10lib/websocket: fix possible data race on ClientShulhan
The Client have method send that check if the underlying connection (conn) has been closed or not. Since the conn can be closed anytime, for example server send to the control CLOSE frame: recv -> handleFrame -> handleClose -> Quit we need to guard the conn with Mutex before calling send to prevent data race.
2022-10-08lib/websocket: rewords some comment and package documentationShulhan
2022-07-29lib/websocket: reformat and paraphrase some commentsShulhan
2022-06-09lib/websocket: refactoring codeShulhan
Replace assignment from using ":=" to use variable declaration with type. Rationale: clarity and minimize duplicate temporary variables with the same type.
2022-06-09lib/websocket: realign all struct to minimize allocationsShulhan
Changes, * Client: from 176 to 144 (-32 bytes) * ClientManager: from 64 to 40 (-24 bytes) * Request: from 88 to 72 (-16 bytes) * Response: from 40 to 24 (-16 bytes) * route: from 48 to 32 (-16 bytes) * Server: from 72 to 64 (-8 bytes) * ServerOptions: from 104 to 96 (s-8 bytes) Plus other structs in the tests.
2022-05-09all: reformat all codes using gofmt 1.19 (the Go tip)Shulhan
2021-04-06websocket: suppress error on calling handleCloseShulhan
The handleClose is a function that will be called when client receive control CLOSE frame from server. Default handle is to response with control CLOSE frame with the same payload. This field is not exported, and only defined to allow testing.
2020-10-23websocket: set TLSConfig to nil if Endpoint scheme is not https or wssShulhan
If user set TLSConfig but the Endpoint is not start with "https" or "wss", client open() method may return an error "Connect: tls: first record does not look like a TLS handshake". This commit fix inconsistencies between TLSConfig and Endpoint scheme.
2020-08-11websocket: reformat some filesShulhan
2020-06-06all: use default linter optionsShulhan
2020-05-11websocket: allow "https" scheme on Client's EndpointShulhan
Previously, we only check for "wss" scheme to initialize the TLS configuration. At some point, user may have one single address to connect to HTTP and WebSocket server on the same domain, which require two addresses on their side. This commit relaxing the Endpoint rule when parsing WebSocket URI. Scheme "https" will be considered as "wss" or secure connection with TLS.
2020-04-29websocket: lock the connection when processing CloseShulhan
2020-04-29websocket: add routine that send PING control frame on ConnectShulhan
The send interval can be set in Client.PingInterval. The minimum and default value is 10 seconds.
2020-04-29websocket: add method to gracefully Close the client connectionShulhan
The Close method send the control CLOSE frame to server and wait for the CLOSE response. This changes unexport the SendClose method.
2020-02-16websocket: allow custom TLS configuration on clientShulhan
This change will allow the client to use client certificate when connecting to WebSocket server with self-signed certificate.
2019-11-14websocket: check for read timeout on recvShulhan
2019-10-21all: fix and add missing commentsShulhan
2019-06-14all: fix nolint formatShulhan
The valid syntax to suppress linter warnings is "//nolint:<name>" with no space between comment and "nolint" and between ":". Also, we move the placement of nolint directive to the top of statements for multiple nolint in the same scope. While at it, fix and supress some linter warnings.
2019-03-20websocket: use custom HTTP parser for clientShulhan
The problem with using the standard http.ReadResponse is that the received packet may contains WebSocket frame, not just HTTP response. This cause the initial frame lost, which may required by client (for example, as a response for authentication).
2019-03-17websocket: update log related formatShulhan
Use "fmt" package when printing debugging information, and "log" package when printing error.
2019-03-17websocket: simplify client handshake process without handler and contextShulhan
User of library that want to create WebSocket client should only focus to the Endpoint and/or Headers when creating client. While at it, change handshake test to check for error instead of status code.
2019-03-17websocket: call Quit when client receive error or empty packetShulhan
Empty packet may indicated that server has closed the connection abnormally and we need to close the socket clearly.
2019-03-17websocket: fix empty path when generating client handshake requestShulhan
Also, check if the Endpoint URL contains query parameter before appending the "?" to handshake request path.
2019-03-17websocket: add handler when client connection closedShulhan
The handler is called HandleQuit and can be used to clean resource or reconnect to server. Default is nil.
2019-03-17websocket: remove mutex on clientShulhan
Since the client receive is now unexported, handled internally, and handler are centralized, there is no need to lock when doing write and read on socket anymore. The lock is still required when closing the socket, to prevent multiple routines call Quit at the same time.
2019-03-17websocket: pass the instance of client to handlerShulhan
Since handler are created before creating a client and a handler may send a response to server after receiving a message from server, we pass the current client to handler as parameter.
2019-03-17websocket: move isValidFrame as method of FrameShulhan
This is to minimize duplicate code on client and server.
2019-03-17websocket: simplify handling chopped frameShulhan
Previously, we use two function to unpack frame: frameUnpack and continueUnpack, both of this functions actually use the same logic. This commit merge both functions into Frame's unpack() and which also make handleChopped() to be unused on both server and client.
2019-03-17websocket: rewrite client to use centralized handlerShulhan
Unlike HTTP client or other most commmon TCP oriented client, the WebSocket client is actually asynchronous or passive-active instead of synchronous. At any time client connection is open to server, client can receive a message broadcast from server. Case examples: if client send "A" to server, and expect that server response with "A+", server may send message "B" before sending "A+". Another case is when client connection is open, server may send "B" and "C" in any order without any request send by client previously. Due to this model, the way to handle response from server is centralized using handlers instead of using single send request-response.
2019-03-12websocket: export the opcode typeShulhan
The opcode type is required to create new frame and to get the opcode in continous frames.
2019-03-07websocket: remove instance of bytes.Buffer from Client's fieldShulhan
Since bytes.Buffer only used once, on client handshake, there is no need to keep it on Client.
2019-03-07websocket: add mutex to prevent data race on send or receive on ClientShulhan
This is to enable single client to be used on multiple routines.
2019-03-07websocket: remove pool of slice bytesShulhan
2019-03-07websocket: add unit test for client SendClose and QuitShulhan
Also, make sure we close the client connection from unit test.
2019-03-07websocket: use client recv method on RecvShulhan
This is to minimize duplicate code on client.
2019-03-07websocket: remove client connection stateShulhan
Previously, client connection state is used to disallow send or receive if client is not connected to remote server. This check also can be done by checking for nil on connection field.
2019-03-07websocket: add unit test for client SendBin() and SendPing()Shulhan
Changes caused by test: * handlePing become the internal field of client instead of method, so it can be replaced during test * add internal context ctxKeyFrame to save the expected frame in handler
2019-03-06websocket: stop the pingQueue routine when client closedShulhan
This will make sure no routine is leaked if client want to reconnect again.