I've been working on a hobby project for a few months, an MIT licensed API gateway designed to be independent of any particular vendor. I think it's going quite well, to be honest. As my code base has grown, I've seen opportunity for improvement around the core, that being the HTTP server. Spinning out the core HTTP server into its own micro-framework seemed like a logical solution (and a great learning exercise!).
Introducing Kindling, the fuel that'll ignite your application. Kindling is based on the standard Java 21 library, with no dependencies. It's designed to be programmable, without using any magic.
Here's a simple Hello World with Kindling:
package io.kerosenelabs.kindling; import java.nio.file.Path; import java.util.HashMap; import io.kerosenelabs.kindling.constant.HttpMethod; import io.kerosenelabs.kindling.constant.HttpStatus; import io.kerosenelabs.kindling.exception.KindlingException; import io.kerosenelabs.kindling.handler.RequestHandler; public class Main { public static void main(String[] args) throws KindlingException { KindlingServer server = KindlingServer.getInstance(); // test request handler server.installRequestHandler(new RequestHandler() { /** * Tell the server what type of request this handler can work with */ @Override public boolean accepts(HttpMethod httpMethod, String resource) throws KindlingException { return httpMethod.equals(HttpMethod.GET) && resource.equals("/"); } /** * Do your business logic here */ @Override public HttpResponse handle(HttpRequest httpRequest) throws KindlingException { return new HttpResponse.Builder() .status(HttpStatus.OK) .headers(new HashMap<>() { { put("Content-Type", "text/html"); } }) .content("<h1>Hello from Kindling!</h1>") .build(); } }); // serve our server server.serve(8443, Path.of("mykeystore.p12"), "password"); } }
Sending a CURL request to the server yields this response:
> GET / HTTP/1.1 > Host: localhost:8443 > User-Agent: curl/7.88.1 > Accept: */* > * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): < HTTP/1.1 200 OK < Content-Type: text/html * no chunk, no close, no size. Assume close to signal end < * TLSv1.3 (IN), TLS alert, user canceled (346): * TLSv1.3 (IN), TLS alert, close notify (256): * Closing connection 0 * TLSv1.3 (OUT), TLS alert, close notify (256): <h1>Hello from Kindling!</h1>
...pretty cool, right?
There's a few bugs, like Content-Length being missing in the response.
The above is the detailed content of Building a web server with no dependencies in Java. For more information, please follow other related articles on the PHP Chinese website!