Create a gist now

Instantly share code, notes, and snippets.

A simple server in Frege.
module Server where
import frege.java.IO hiding (OutputStream)
data Executor = native java.util.concurrent.Executor
data InetSocketAddress = native java.net.InetSocketAddress where
native new :: Int -> STMutable s InetSocketAddress
data HttpServer = native com.sun.net.httpserver.HttpServer where
native create "com.sun.net.httpserver.HttpServer.create" :: Mutable s InetSocketAddress -> Int -> STMutable s HttpServer throws IOException
native createContext :: MutableIO HttpServer -> String -> MutableIO HttpHandler -> IO ()
native setExecutor :: MutableIO HttpServer -> Maybe Executor -> IO ()
native start :: MutableIO HttpServer -> IO ()
data OutputStream = mutable native java.io.OutputStream where
native write :: OutputStream -> ArrayOf RealWorld Byte -> IO () throws IOException
native close :: OutputStream -> IO () throws IOException
data StringAsBytes = native java.lang.String where
native getBytes :: String -> STMutable s (JArray Byte)
data HttpExchange = native com.sun.net.httpserver.HttpExchange where
native getResponseBody :: MutableIO HttpExchange -> IO OutputStream
native sendResponseHeaders :: MutableIO HttpExchange -> Int -> Long -> IO () throws IOException
data HttpHandler = native com.sun.net.httpserver.HttpHandler where
-- substitute for a constructor
native new Server.Handler.newInstance :: (MutableIO HttpExchange -> IO ()) -> STMutable s HttpHandler
response :: String
response = "<h1>It worked!!</h1>"
handle :: MutableIO HttpExchange -> IO ()
handle t = do
t.sendResponseHeaders 200 (length response).long
os <- t.getResponseBody
bytes <- StringAsBytes.getBytes response
os.write bytes
os.close
native module where {
public static class Handler implements com.sun.net.httpserver.HttpHandler {
final frege.run7.Func.U handlerFunction;
public Handler(frege.run7.Func.U function){
this.handlerFunction = function;
}
public static Handler newInstance(frege.run7.Func.U function) {
Handler h = new Handler(function);
return h;
}
@Override
public void handle(com.sun.net.httpserver.HttpExchange t) throws java.io.IOException {
try {
final frege.run7.Func.U res = RunTM.<frege.run7.Func.U>cast(handlerFunction.apply(Thunk.lazy(t)).call());
frege.prelude.PreludeBase.TST.run(res).call();
} catch (Exception e) {
System.out.println("Failed to execute handler");
}
}
}
}
main args = do
inet <- InetSocketAddress.new 8000
server <- HttpServer.create inet 0
handler <- HttpHandler.new handle
server.createContext "/" handler
server.start
println "Serving HTTP on 0.0.0.0 port 8000"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment