首頁 > Java > java教程 > 主體

用 Java 建立一個不依賴任何依賴的 Web 伺服器

王林
發布: 2024-08-09 10:20:50
原創
710 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!