-
-
Save lucasrpb/c86db07a95e9718c37841200923effa9 to your computer and use it in GitHub Desktop.
A very simple Finagle HTTP server example (no error handling, etc.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scalaVersion := "2.11.4" | |
libraryDependencies += "com.twitter" %% "finagle-http" % "6.24.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment