JonathanGiles / TeenyHttpd

TeenyHttpd is a HTTP server written in Java.
MIT License
17 stars 3 forks source link

Readme updates for teenyApplication #4

Closed JonathanGiles closed 9 months ago

JonathanGiles commented 9 months ago

FYI - @alex-cova - please suggest changes or additional text into the PR, and we can work on it until it covers the features.

alex-cova commented 9 months ago

We should omit the ##Configuration section 'cause it can be described in ##Message Converters

For example:

Message Converters

TeenyApplication provides support for custom message converters. These converters are used to handle specific content types as specified by the user.

For example the following code handles requests of content type application/json

public class GsonMessageConverter implements MessageConverter {

    final Gson gson = new Gson();

    @Override
    public String getContentType() {
        return "application/json";
    }

    @Override
    public void write(Object value, BufferedOutputStream dataOut) throws IOException {

        if (value instanceof String) {
            dataOut.write(((String) value).getBytes());
            return;
        }

        dataOut.write(gson.toJson(value).getBytes());
    }

    @Override
    public Object read(String value, Type type) {

        if (String.class.isAssignableFrom((Class<?>) type)) {
            return value;
        }

        return gson.fromJson(value, type);
    }
}

Similar to Spring, @Configuration is used to provide configurations. To specify a custom MessageConverter, you can define your configuration as shown below.

@Configuration
public GsonMessageConverter getGsonConverter() {
    return new GsonMessageConverter();
}

Would be awesome to omit both of them, but TeenyJson is not finished :S

alex-cova commented 9 months ago

Server-Sent Events

Simply define the handler and give it a name, if no name is specified then the name of the method will be used instead.

@ServerEvent(value = "/messages", name = "messages")
public ServerSentEventHandler chatMessages() {
    return ServerSentEventHandler.create();
}

Use it directly anywhere.

Post("/message")
public void message(@QueryParam("message") String message,
                        @EventHandler("messages") ServerSentEventHandler chatMessagesEventHandler) {

        chatMessagesEventHandler.sendMessage(message);
    }

Similar to the ChatServer demo application, Here you can find the same example but using annotations.