首页  >  文章  >  Java  >  用 Java 构建一个不依赖任何依赖的 Web 服务器

用 Java 构建一个不依赖任何依赖的 Web 服务器

王林
王林原创
2024-08-09 10:20:50633浏览

Building a web server with no dependencies in Java

我已经在一个业余爱好项目上工作了几个月,这是一个 MIT 许可的 API 网关,旨在独立于任何特定供应商。老实说,我认为一切进展顺利。随着我的代码库的增长,我看到了围绕核心(即 HTTP 服务器)进行改进的机会。将核心 HTTP 服务器拆分为自己的微框架似乎是一个合乎逻辑的解决方案(也是一次很棒的学习练习!)。

引入 Kindling,它将点燃您的应用程序的燃料。 Kindling 基于标准 Java 21 库,没有依赖项。它被设计为可编程的,无需使用任何魔法。

这是一个使用 Kindling 的简单 Hello World:

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");
    }
}

向服务器发送 CURL 请求会产生以下响应:

> 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>

...很酷,对吧?

存在一些错误,例如响应中缺少 Content-Length。

以上是用 Java 构建一个不依赖任何依赖的 Web 服务器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn