Skip to content

Latest commit

 

History

History
175 lines (135 loc) · 4.96 KB

README.md

File metadata and controls

175 lines (135 loc) · 4.96 KB

Rest4j

HTTP wrapper that sits on top of different HTTP Server implementations. Bring Your Own Server (BYOS).

Inspiration from the Go stdlib http package.

Table of Contents

  1. Download
  2. Implemented Servers
  3. Usage & Examples
  4. Middleware
  5. Chaining Routers
  6. Static resources

Download

Gradle

dependencies {
    compile 'com.github.while-loop:rest4j:1.0.4'
}

Maven

<dependency>
    <groupId>com.github.while-loop</groupId>
    <artifactId>rest4j</artifactId>
    <version>1.0.4</version>
</dependency>

Implemented Servers

Usage

For a full demo example, check the integration package

public class Example {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8080), 0);

        Router r = new Router();
        r.handle("/", (req, resp) -> {
            String raddr = req.remoteAddr();

            resp.headers.set("Content-Type", "text/plain");
            resp.write("hello " + raddr + "!!");
        });
        r.handle("/:uuid", Example::update).setMethods(PUT);

        server.createContext("/", new SunRouter(r)); // BYOS
        server.setExecutor(Executors.newSingleThreadExecutor());
        server.start();
    }

    private static void update(HttpRequest req, HttpResponse resp) {
        String body = is2String(req);
        String uuid = req.getParam("uuid");
        // do something with body

        resp.writeHeader(ACCEPTED);
    }

    private static String is2String(InputStream is) {
        try (java.util.Scanner s = new java.util.Scanner(is, StandardCharsets.UTF_8.name())) {
            s.useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
    }
}

Middleware

public class LoggerMiddleware implements Middleware {
    private Logger logger;

    public LoggerMiddleware() {
        this(null);
    }

    public LoggerMiddleware(Logger logger) {
        if (logger == null) {
            logger = LoggerFactory.getLogger(LoggerMiddleware.class);
        }

        this.logger = logger;
    }

    @Override
    public Handler handle(Handler next) {
        return (req, resp) -> {
            // get the time before passing the request down the chain of middleware
            long start = System.currentTimeMillis();

            next.handle(req, resp); // apply the next handle

            long elapsed = System.currentTimeMillis() - start;
            logger.info(String.format("%-7s %-6s %d %s",
                    req.getMethod(), elapsed + "ms", resp.status.code(), req.getUrl().getPath()));
        };
    }
}

Chaining Routers

Router r = new Router();
r.use(new LoggerMiddleware(),
        new JsonMiddleware(),
        new CorsMiddleware());

Router v1 = new Router();
Router usersR = new Router();
usersR.handle("/", this::getAll);                               // GET /v1/users
usersR.handle("/:uuid", this::updateUser).setMethods(PUT);     // PUT /v1/users/:uuid
usersR.handle("/:uuid", this::deleteUuser).setMethods(DELETE); // DELETE /v1/users/:uuid

Router postsR = new Router();
usersR.handle("/", this::getAll);                                   // GET /v1/posts
usersR.handle("/:postId", this::updatePost).setMethods(PUT);       // PUT /v1/posts/:uuid
usersR.handle("/:postId", this::deletePost).setMethods(DELETE);    // DELETE /v1/posts/:uuid

v1.handle("/users", usersR); // /v1/users
v1.handle("/posts", usersR); // /v1/posts
r.handle("/v1", v1); // /v1

Static Resources

String dir = getClass().getClassLoader().getResource("www").toExternalForm();
FileHandler fh = new FileHandler(dir);

Changelog

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

CHANGELOG.md

License

rest4j is licensed under the Apache 2.0 License. See LICENSE for details.

Author

Anthony Alves