Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Last active March 2, 2017 02:49
Show Gist options
  • Save travisbrown/ccdab82869f227aeade8 to your computer and use it in GitHub Desktop.
Save travisbrown/ccdab82869f227aeade8 to your computer and use it in GitHub Desktop.
A very simple Finagle HTTP server example (no error handling, etc.)
scalaVersion := "2.11.4"
libraryDependencies += "com.twitter" %% "finagle-http" % "6.24.0"
import com.twitter.finagle.Http;
import com.twitter.finagle.ListeningServer;
import com.twitter.finagle.Service;
import com.twitter.finagle.http.HttpMuxer;
import com.twitter.util.Await;
import com.twitter.util.Future;
import java.net.InetSocketAddress;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.jboss.netty.buffer.ChannelBuffers.copiedBuffer;
import org.jboss.netty.handler.codec.http.*;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpMuxer muxService = new HttpMuxer().withHandler("/calc", new CalcService());
ListeningServer server = Http.serve(new InetSocketAddress(8000), muxService);
System.out.println("The server Alive and Kicking");
Await.ready(server);
}
}
class CalcService extends Service<HttpRequest, HttpResponse> {
public Future<HttpResponse> apply(HttpRequest req) {
QueryStringDecoder decoder = new QueryStringDecoder(req.getUri());
// Do your calculation here.
int param = Integer.parseInt(decoder.getParameters().get("param").get(0));
String result = Integer.toString(param);
StringBuilder content = new StringBuilder();
content.append("<html><body>");
content.append(result + "<br/>");
content.append("</body></html>");
HttpResponse response = new DefaultHttpResponse(
req.getProtocolVersion(),
HttpResponseStatus.OK
);
response.setContent(copiedBuffer(content.toString(), UTF_8));
return Future.value(response);
}
}
@travisbrown
Copy link
Author

See this thread for context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment