Web Server Tutorial
Most documents and articles regarding to Light-4j are about RESTful or GraphQL or Hybrid services; however, there are a lot user cases that combine the API and static site rendering together, particularly single page applications built on top of React or Angular.
As we know, the light-4j needs a plugin to inject application logic and for API project that is based on OpenAPI specification, this is generated by the light-codegen.
The generated Handler Provider maps each endpoint to a corresponding handler generated. For API server that need to serve static content along with APIs, we need to wrap this map with Resource handler to serve static content. On top of resource handler, we need a predicates handler to rewrite request to index.html which can loaded your single page application.
In the example web server, I redirect to index.html if path is not in the following list.
The above rules make sure that images and other asserts(css etc) can be loaded and API endpoint will be started as /api/xxx
Web Server Configuration
In most cases, each APP or API built on top of light-4j framework will has a configuration file to control how it behaves during runtime. Here is the content of webserver.yml
base: "/public" transferMinSize: '100'
Given that the base is defined as /public, we know the static content root will be /public in host file system and all static content will be served from this folder or sub folders.
Location of static content
As light-4j applications are packaged as a jar so the static content must be served from somewhere from the file system. The location of these static files can be configured by webserver.yml and it can be externalized.
The above section describes how to serve static content from packaged jar file and it is only suitable for development. When you deploy the app/api to official environment with docker container, the /public must be externalized so that website can be updated independently without repackage the server.
Here is the Dockerfile in the example.
FROM insideo/jre8 EXPOSE 8080 ADD /target/webserver-0.1.0.jar server.jar ADD src/main/resources/public /public CMD ["/bin/sh","-c","java -Dlight-4j-config-dir=/config -jar /server.jar"]
The static contant in src/main/resources/public is added to the /public in the contain and this folder can be mapped to host directory with -v if you want to update the site in host file system.
This example is very useful in self contained microservices that has a very simple UI built on top of React or Angular. It give you an interface to interact with the services running on the same instance.