Skip to content

Simple http server (Java)

Oleksandr Loushkin edited this page Oct 9, 2017 · 1 revision

Java based config

package ua.com.lavi.komock;

import ua.com.lavi.komock.http.server.MockServer;
import ua.com.lavi.komock.http.server.UnsecuredMockServer;
import ua.com.lavi.komock.model.HttpMethod;
import ua.com.lavi.komock.model.config.http.HttpServerProperties;
import ua.com.lavi.komock.model.config.http.RouteProperties;

import java.util.Collections;

/**
 * Created by Oleksandr Loushkin on 01.09.17.
 */
public class SimpleJavaMockServer {

    public static void main(String[] args) {
        HttpServerProperties serverProperties = new HttpServerProperties()
                .withRoutes(Collections.singletonList(firstRoute()))
                .withName("simple")
                .withPort(9090);
        MockServer mockServer = new UnsecuredMockServer(serverProperties);
        mockServer.start();

        mockServer.addRoute(secondRoute());
    }

    private static RouteProperties firstRoute() {
        RouteProperties routeProperties = new RouteProperties();
        routeProperties.setHttpMethod(HttpMethod.GET.name());
        routeProperties.setCode(200);
        routeProperties.setContentType("application/json");
        routeProperties.setResponseBody("{\"name\" : \"value\"}");
        routeProperties.setUrl("/testUrl");
        return routeProperties;
    }

    private static RouteProperties secondRoute() {
        RouteProperties routeProperties = new RouteProperties();
        routeProperties.setHttpMethod(HttpMethod.GET.name());
        routeProperties.setCode(200);
        routeProperties.setContentType("text/plain");
        routeProperties.setResponseBody("hey, this is a response!");
        routeProperties.setUrl("/testUrl2");
        return routeProperties;
    }
}

The FirstRoute added by configuration.

The SecondRoute added by additional method call in runtime.

Equals yaml config

httpServers:
  -
    name: simple
    port: 9090
    routes:
      -
        httpMethod: GET
        url: /testUrl
        contentType: application/json
        responseBody: '{"name" : "value"}'
        code: 200
      -
        httpMethod: GET
        url: /testUrl2
        contentType: text/plain
        responseBody: hey, this is a response!
        code: 200

Testing by curl:

Run

curl http://127.0.0.1:9090/testUrl

You should get the following response:

{"name" : "value"}

Run

curl http://127.0.0.1:9090/testUrl2

You should get the following response:

hey, this is a response!
Clone this wiki locally