EzyHTTP Serves Static Files

Updated at 1685686503000
Static files maybe are html, css, images, ... and EzyHttp server can help you provide static files to client via asynchronous APIs.

1. Why does EzyHTTP use asynchronous APIs?

Static files is heavy, it can take seconds or minutes to response to client completely. But in a server, we usually use a limit of threads for request handlers. Let's say we have 8 threads, now client 1st download 8 files with 10MB for each file. Server will use entire 8 threads to serve client 1st. Now client 2nd will must wait for server to have free threads. The consequence is server can not serve many clients at the same time. In the bellow image, server's using 3 threads to handle 3 requests.

The solution is asynchronous mechanism with even loop and blocking queue. We can use 4 threads for even loop. When client 1st wants to download 8 files, they're equalival 8 requests, we will push these 8 files to the queue. When client 2nd want to download files, we continuously push it's requests to the queue. The event loop will do like this:

loop:
    take a request from the queue:
        take 1024 bytes from the inputstream of the requested file and push to client's outputstream
        if there is no remain data in the inputstream
            then response to the client: done
        else
            push the request back to the queue

for this way, server can serve many client at the same time, and server can allocate resources for every request equally. In the bellow image server has an even loop to handle heavy requests and 2 threads for light requests

2. Configuration

In default, EzyHTTP disables static files serve. To enable it, you put to your application.properties file:

resources.enable: true

For application.yml, the setting is:

resources:
  enable: true

Now you can place your static file to src/main/resources/static folder, example:

For the static files in the above image, EzyHTTP server will generate 2 APIs:

  1. /css/style.css
  2. /js/main.js

If don't want to use static folder, you can use specific another folders by configuration:

resources.locations=folder1,folder2

EzyHTTP will map an API for each static file, so you don't need worry about hacker can walk any files outside static folder.