All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rx.net.http.ServerResponse Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.net.http;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.rx.io.Bytes;

import static org.rx.core.Sys.toJsonString;

@RequiredArgsConstructor
@Getter
public class ServerResponse {
    public static final AsciiString APPLICATION_JSON = AsciiString.cached("application/json; charset=UTF-8");
    public static final AsciiString TEXT_HTML = AsciiString.cached("text/html; charset=UTF-8");
    private final HttpHeaders headers = new DefaultHttpHeaders();

    public void addCookie(Cookie cookie) {
        headers.add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
    }

    public void setContentType(String contentType) {
        headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
    }

    @Setter
    private ByteBuf content;

    public void jsonBody(Object json) {
        setContentType(APPLICATION_JSON.toString());
        content = Bytes.directBuffer();
        content.writeCharSequence(toJsonString(json), CharsetUtil.UTF_8);
    }

    public void htmlBody(String html) {
        setContentType(TEXT_HTML.toString());
        content = Bytes.directBuffer();
        content.writeCharSequence(html, CharsetUtil.UTF_8);
    }

    public void redirect(String newUri) {
        headers.set(HttpHeaderNames.LOCATION, newUri);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy