aboutsummaryrefslogtreecommitdiff
path: root/lib/http
AgeCommit message (Collapse)Author
11 daysall: apply go fixShulhan
2026-02-15lib/http: fix possible data race in SSE connectionShulhan
When server's handler call Write or WriteRaw, there is possibility that the worker for keeping the connection alive also call Write at the same time, which cause the data race.
2026-02-13lib/http: realign the fields in struct ServerShulhan
Previous struct size is 384 pointer bytes, now realign to 336 bytes (-48 bytes).
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-11lib/http: add BasePath to the ServerOptionsShulhan
The BasePath allow server to serve HTTP from custom prefix, other than "/". Each request that server received will remove the BasePath first from the [http.Request.URL.Path] before passing to the handler. Each redirect that server sent will add the BasePath as the prefix to redirect URL. Any trailing slash in the BasePath will be removed.
2026-02-05lib/http: change HandleFS redirect status code to 301 Moved PermanentlyShulhan
According to MDN [Redirections in HTTP], the HTTP status 302 Found use case is The Web page is temporarily unavailable for unforeseen reasons. This probably to re-route the page until the original page is fixed. While HTTP status 301 is for Reorganization of a website. Since the redirection in HandleFS only happen when user access directory without slash, we should make it permanent. [Redirections in HTTP]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Redirections
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-02-02lib/http: add field Listener to ServerOptionsShulhan
The field Listener allow user to pass [net.Listener] for accepting new connection using [http.Serve] or [http.ServeTLS].
2026-01-15all: convert license and copyright to use SPDX identifiersShulhan
With help of spdxconv tool [1], we able to bulk update all files license and copyright format to comply with SPDX formats. [1] https://kilabit.info/project/spdxconv/
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-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.
2025-01-25lib/http: return an error when parsing Content-RangeShulhan
Instead of returning nil only, return the error to report the input parameter back to the caller.
2025-01-23all: use for-range with numericShulhan
Go 1.22 now support for-range on numeric value.
2025-01-23all: replace "interface{}" with "any"Shulhan
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-12-28lib/http: simplify setting Client TransportShulhan
While at it, set the ExpectContinueTimeout using the Timeout from ClientOptions.
2024-12-28lib/http: add method to return default HTTP Transport in ClientShulhan
The returned [http.Transport] is created after the Client instantiated. Their value can be customized by user when needed, which should affect the Transport inside the Client.
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-06-08lib/http: add request type HTMLShulhan
The RequestTypeHTML define the content type "text/html".
2024-05-04lib: comply with linter recommendationsShulhan
2024-04-24lib/http: refactoring "multipart/form-data" parameters in ClientRequestShulhan
Previously, ClientRequest with type RequestTypeMultipartForm pass the type "map[string][]byte" in Params. This type hold the file upload, where key is the file name and []byte is content of file. Unfortunately, this model does not correct because a "multipart/form-data" can contains different field name and file name, for example --boundary Content-Disposition: form-data; name="field0"; filename="file0" Content-Type: application/octet-stream <Content of file0> This changes fix this by changing the parameter type for RequestTypeMultipartForm to [*multipart.Form], which affect several functions including [Client.PutFormData] and [GenerateFormData]. We also add new function [CreateMultipartFileHeader] to help creating [multipart.FileHeader] from raw bytes, that can be assigned to [*multipart.Form].
2024-04-23lib/http: allow all HTTP method to generate HTTP request with bodyShulhan
Althought the RFC 7231 says that no special defined meaning for a payload in GET, some implementation of HTTP API sometimes use GET with content type "application/x-www-form-urlencoded".
2024-03-26lib/http: remove unnecessary second return value in getFSNodeShulhan
The second return valus is a boolean to indicate that node is directory, which can also retrieved from Node using method IsDir.
2024-03-21lib/memfs: trim trailing slash ("/") in the path of Get methodShulhan
The MemFS always store directory without slash. If caller request a directory node with slash, it will always return nil.
2024-03-15lib/http: refactoring FSHandler type to return [*memfs.Node]Shulhan
Changing FSHandler type to return [*memfs.Node], allow the handler to redirect or return custom node. One of the use case is when service Single Page Application (SPA), where route is handled by JavaScript. For example, when user requested "/dashboard" but dashboard directory does not exist, one can write the following handler to return "/index.html", { node, _ = memfs.Get(`/index.html`) return node }
2024-03-15lib/http: refactoring type of ResponseType from int to stringShulhan
The reason is to make storing or encoding the value readable from human point of view instead of number, 0, 1, 2, etc.
2024-03-15lib/http: refactor type of RequestType from int to stringShulhan
The reason is to make storing or encoding the RequestType value readable from human point of view instead of number, 0, 1, 2, etc.
2024-03-15lib/http: refactoring type of RequestMethod from int to stringShulhan
The reason is to make storing or encoding the RequestMethod value readable from user point of view instead of number, 0, 1, 2, etc.
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 benchmark for Server handleDelete and registerDeleteShulhan
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: rename files for consistencyShulhan
If the type is in CamelCase the file should be using snake_case.
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-05lib/http: move CORS initialization and handler to cors_optionsShulhan
This is to decoupling between ServerOptions and Server handlers.
2024-03-05lib/http: handle CORS independentlyShulhan
Previously, if [CORSOptions.AllowOrigins] not found we return it immediately without checking request "Access-Control-Request-Method", "Access-Control-Request-Headers", and other CORS options. This changes check each of them, a missing allow origins does not means empty allowed method, headers, MaxAge, or credentials.
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-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-20lib/http: add constanta for header Set-CookieShulhan
2024-02-15all: set unused parameter to "_"Shulhan
2024-02-15lib/http: export function to generate "multipart/form-data"Shulhan
The GenerateFormData generate the request body with boundary for HTTP content-type "multipart/form-data" from map[string][]byte.
2024-01-25lib/path: new package to work with pathShulhan
The path package provide a new type Route, detached from "lib/http". A Route represent a parsed path. A path can have a key, or binding, that can be replaced with string value. For example, "/org/:user/:repo" have two keys "user" and "repo". Route handle the path in case-insensitive manner.
2024-01-24lib/http: simplify parameter names in Client method for godocShulhan
The Client methods when rendered in godoc is quite long make it uneasy to read.
2024-01-24lib/http: add support for If-Modified-Since in HandleFSShulhan
If the node modification time is less than requested time value in request header If-Modified-Since, server will response with 304 Not Modified.
2024-01-24lib/http: use raw string literal for string constantsShulhan
While at it, group the constants by its values.
2024-01-24lib/http: update doc to use comment linksShulhan