aboutsummaryrefslogtreecommitdiff
path: root/lib/http/server_test.go
AgeCommit message (Collapse)Author
2026-02-11lib/http: implement server auto shutdown when idleShulhan
In the `ServerOptions`, we add option `ShutdownIdleDuration` when set to non-zero value it will start a timer. When the timer expired, the server will stop accepting new connection and then shutting down. This allow de-activating HTTP server when no connections received after specific duration to reduce the system resources.
2026-02-05lib/http: handle file system with canonical directory end with slash "/"Shulhan
Previously, if request to directory does not end with "/", the HTTP server will return the index.html of that directory. This cause relative link inside the index.html broken when visited from browser. This changes make the request to directory always end with "/" by redirecting the request with status 303 Found.
2026-01-06lib/http: add second return value, statusCode, to FSHandlerShulhan
Non-zero status code indicates that the function already response to the request, and the server will return immediately. Zero status code indicates that the function did not process the request, it is up to server to process the returned node `out`.
2025-01-22lib/http: always refresh a directory on GET requestShulhan
On server with TryDirect is true, any GET request to a directory should always rescan the content and the generate the new index.html. While at it, return the generated time in UTC instead of local time.
2024-09-30lib/http: add Server method to register handler by functionShulhan
The RegisterHandleFunc register a pattern with a handler, similar to [http.ServeMux.HandleFunc]. The pattern follow the Go 1.22 format: [METHOD] PATH The METHOD is optional, default to GET. The PATH must not contains the domain name and space. Unlike standard library, variable in PATH is read using ":var" not "{var}". This endpoint will accept any content type and return the body as is; it is up to the handler to read and set the content type and the response headers. If the METHOD and/or PATH is already registered it will panic.
2024-09-30lib/http: remove writing StatusNoContent on ResponseTypeNodeShulhan
To make consistent with RequestTypeNone, the ResponseTypeNone should not write any response header or HTTP status code. It will be handled manually by [Endpoint.Call].
2024-03-15lib/http: refactoring Client methods to return struct ClientResponseShulhan
Instead of returning three variables, [http.Response], []byte, and error, we combine the [http.Response] and []byte into single struct: ClientResponse.
2024-03-14lib/http: refactor Client methods to use struct ClientRequestShulhan
2024-03-14lib/http: add test for Server handleDeleteShulhan
2024-03-09lib/http: refactoring NewServer and NewClientShulhan
The NewServer and NewClient now accept non-pointer options, so the caller unable to modify the options once the server or client has been created.
2024-03-09lib/http: refactor of RegisterEndpoint and RegisterSSE to non-pointerShulhan
Once the endpoint registered, the caller should not able to changes any values on endpoint again.
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-05all: comply with linter recommendations #1Shulhan
Instead of annotating the lines that caught by linters, fix it to comply with the recommendations. This causes several breaking changes, especially related to naming, * api/slack: [Message.IconUrl] become [Message.IconURL] * lib/dns: DefaultSoaMinumumTtl become DefaultSoaMinimumTTL * lib/email: [Message.SetBodyHtml] become [Message.SetBodyHTML] * lib/http: [Client.GenerateHttpRequest] become [Client.GenerateHTTPRequest] * lib/http: [ClientOptions.ServerUrl] become [ClientOptions.ServerURL] * lib/http: [EndpointRequest.HttpWriter] become [EndpointRequest.HTTPWriter] * lib/http: [EndpointRequest.HttpRequest] become [EndpointRequest.HTTPRequest] * lib/http: [ServerOptions.EnableIndexHtml] become [ServerOptions.EnableIndexHTML] * lib/http: [SSEConn.HttpRequest] become [SSEConn.HTTPRequest] * lib/smtp: [ClientOptions.ServerUrl] become [ClientOptions.ServerURL] * lib/ssh/sftp: [FileAttrs.SetUid] become [FileAttrs.SetUID] * lib/ssh/sftp: [FileAttrs.Uid] become [FileAttrs.UID]
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
2024-02-15all: set unused parameter to "_"Shulhan
2024-01-24lib/http: refactoring Range request, limit content served by serverShulhan
When server receive, GET /big Range: bytes=0- and the requested resources is quite larger, where writing all content of file result in i/o timeout, it is best practice [1][2] if the server write only partial content and let the client continue with the subsequent Range request. In the above case, the server should response with, HTTP/1.1 206 Partial content Content-Range: bytes 0-<limit>/<size> Content-Length: <limit> Where limit is maximum packet that is reasonable [3] for most of the client. In this server we choose 8MB as limit. [1]: https://stackoverflow.com/questions/63614008/how-best-to-respond-to-an-open-http-range-request [2]: https://bugzilla.mozilla.org/show_bug.cgi?id=570755 [3]: https://docs.aws.amazon.com/whitepapers/latest/s3-optimizing-performance-best-practices/use-byte-range-fetches.html
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-13lib/ascii: replace package "math/rand" with "crypto/rand"Shulhan
Since Go 1.20 the "math/rand.Seed" is considered deprecated (the initial value of rand is seeded automatically, not zero). Now, it is the time to replace "math/rand" with more secure random number generator, from "crypto/rand". This changes affect tests in package "lib/email", "lib/http", and "lib/stmp".
2023-09-11lib/http: realign struct for better size allocationShulhan
The realignment reduce the cost of the following struct, * EndpointResponse: from 72 to 56 bytes (-16 bytes) * RangePosition: from 48 to 24 bytes (-24 bytes) * testCase in TestParseContentRange: from 24 to 16 bytes (-8 bytes)
2023-03-12lib/http: add integration test for request HEAD for RangeShulhan
The test check the response header, whether the Accept-Ranges printed or not.
2023-03-12lib/http: add support for HTTP Range in ServerShulhan
For HTTP Server using HandleFS, the Range request is handled automatically. For other HTTP server, user can use the HandleRange function. The HandleRange function handle [HTTP Range] request using "bytes" unit. The body parameter contains the content of resource being requested that accept Seek method. If the Request method is not GET, or no Range in header request it will return all the body [RFC7233 S-3.1]. The contentType is optional, if its empty, it will detected by http.ResponseWriter during Write. [HTTP Range]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests [RFC7233 S-3.1]: https://datatracker.ietf.org/doc/html/rfc7233#section-3.1 # Conflicts: # CHANGELOG.adoc
2022-10-05lib/http: fix unit tests with -count=X, where X>1Shulhan
Running go test -count=2, for example, will make the second test fail due to call RegisterEndpoint will return an error ErrEndpointAmbiguous.
2022-04-06all: replace any usage of ioutil package with os or ioShulhan
Since Go 1.16, the ioutil package has been deprecated. This changes replace any usage that use functions from ioutil package with their replacement from package os or package io.
2022-03-31lib/http: rewrite ServerOptions FSHandler to handle request in generalShulhan
This changes rename ServerOptions field FSAuthHandler to FSHandler and rewrite their usage. The FSHandler define the function to inspect each GET request to Server MemFS instance. The node parameter contains the requested file inside the memfs. If the handler return true, server will continue processing the node (writing the Node content type, body, and so on). If the handler return false, server stop processing the node and return immediately, which means the function should have already handle writing the header, status code, and/or body.
2022-03-30lib/http: implement handler to authorized request to Server MemfsShulhan
The FSAuthHandler in the ServerOptions define a function that will be called to each GET request to Server Memfs instance using the value from the HTTP Request instance. If the request is not authorized it must return false and the HTTP response will be set to 401 Unauthorized with empty body.
2022-01-30lib/http: change the test port for testing HTTP serverShulhan
Previously, the test port for HTTP server is set to 8080 and may conflict with any service that running on the local (due to common use of 8080). This changes it to 14832 and we make the full server address stored as global variable so any tests can references it.
2021-12-26lib/http: realign all structsShulhan
Changes, * Client: from 56 to 48 bytes (-8 bytes) * CORSOptions: from 104 to 88 bytes (-16 bytes) * Endpoint: from 64 to 32 bytes (-32 bytes) * EndpointRequest: from 72 to 56 bytes (-16 bytes) * route: from 56 to 32 bytes (-24 bytes) Other changes is struct on unit tests.
2021-03-14all: refactoring the test.Assert and test.AssertBench signatureShulhan
Previously, the test.Assert and test.AssertBench functions has the boolean parameter to print the stack trace of test in case its not equal. Since this parameter is not mandatory and its usually always set to "true", we remove them from function signature to simplify the call to Assert and AssertBench.
2021-03-04http: refactoring parameters on Callback and CallbackErrorHandlerShulhan
Previously, the parameters to Callback has three types: the http.ResponseWriter, *http.Request, and []byte for response body. Not only the type names are long, there is no information on the registered Endpoint on the receiver of Callback. This changes wrap the three parameters into single type EndpointRequest with addition field Endpoint, which contains the registered Endpoint. On the CallbackErrorHandler we also have three parameters, but instead of request body we have an error. This changes store the error for CallbackErrorHandler inside EndpointRequest.Error field.
2020-06-06all: use default linter optionsShulhan
2020-05-12http: prefix the header constants with "Header"Shulhan
2020-03-29http: simplify server Endpoint registrationsShulhan
Previously, each endpoint with method DELETE, GET, PATCH, POST, and PUT require calling different call for registration. This change simplify it to one call only, "RegisterEndpoint", and the registration process will be handled automatically based on value on field Method.
2019-12-23errors: add field Name and errShulhan
The field Name is optional, intended to be consumed by program, for example, to provide a key as translation of Message into user's locale defined language. The err field is the underlying error.
2019-09-12http: implement key binding in registered Endpoint's PathShulhan
Previously, only raw path can be registered on Endpoint. This changes implement key binding using colon ":" on path. For example, registering path "/:x/y" will bind key "x" to a string value that can be accessed on http.Request.Form using Get method.
2019-08-07lib/http: make the request body always available even after ParseForm()Shulhan
Previously, if the request type is query, form, or JSON, we call the ParseForm() to let the http.Request read the Body POST form data and fill the Form and/or PostForm fields. This method will cause the request Body will become empty since its already read and closed. One of use case of POST with form data is to check the integrity of POST body using checksum, which is not possible using only ParseForm(). This commit read all the body first into reqBody and recreate the request Body back using ioutil.NopCloser and bytes.Buffer.
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-01-29lib/http: suppress linter warning on global variable on test fileShulhan
2019-01-05lib/http: add parameter http.ResponseWriter to CallbackShulhan
The ResponseWriter can be used to write custom header or to write cookies.
2019-01-05lib/http: rename handler to endpointShulhan
Each route handler now is registered by creating an Endpoint.
2018-12-18lib/http: add evaluator, a middleware between request and handlerShulhan
2018-12-17lib/http: export content type constantsShulhan
2018-12-17lib/http: replace status error with package "lib/errors"Shulhan
2018-12-16lib/http: handle large size of file that is not on memoryShulhan
2018-12-16lib/http: add custom error type for callbackShulhan
Custom error "StatusError" can be used by user to return an error with status code and message.
2018-12-16lib/http: rewrite test to use global callback and single clientShulhan
2018-12-16lib/http: rewrite test to use HTTP client instead of "httptest"Shulhan
This is required to test response header.
2018-12-16lib/http: handle HTTP request OPTIONSShulhan
2018-12-16lib/http: new package for simplifying writing HTTP serverShulhan