Skip to content

Instantly share code, notes, and snippets.

@JohnEarnest
Created May 21, 2013 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnEarnest/5617525 to your computer and use it in GitHub Desktop.
Save JohnEarnest/5617525 to your computer and use it in GitHub Desktop.
A tiny HTTP server written in Java. Requests for resources will serve them up, while requests to a raw directory will execute a shell script named to correspond to the request method, such as "GET". URL arguments are decoded and made available to the shell script as environment variables, making basic dynamic content and form processing possible.
import java.util.*;
import java.net.*;
import java.io.*;
public class Web {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(10101);
while(true) {
Socket s = server.accept();
Scanner in = new Scanner(s.getInputStream());
String method = in.next();
String uri = in.next();
File path = new File(uri.substring(1).split("[?]")[0]);
File base = new File(path.getAbsoluteFile(), method);
PrintWriter out = new PrintWriter(s.getOutputStream());
if (path.isFile() && path.canRead()) {
System.out.println("fetch '"+path+"'");
out.print("HTTP/1.1 200 OK\r\n\r\n");
out.flush();
sendAll(s.getOutputStream(), new FileInputStream(path));
}
else if (base.isFile() && base.canRead()) {
System.out.println("execute '"+base+"'");
Process p = Runtime.getRuntime().exec(
new String[] {"/bin/bash", "-c", "./" + method },
args(uri), path.getAbsoluteFile()
);
p.waitFor();
sendAll(s.getOutputStream(), p.getInputStream());
}
else {
System.out.println("bad request '"+uri+"'");
out.print("HTTP/1.1 400 Bad Request\r\n\r\nSay What?");
}
out.close();
}
}
static String[] args(String uri) throws Exception {
if (uri.indexOf('?') < 0) { return null; }
String[] ret = uri.split("[?]")[1].split("[&]");
for(int z = 0; z < ret.length; z++) {
String[] p = ret[z].split("[=]");
ret[z] = String.format("%s=%s", p[0], URLDecoder.decode(p[1], "UTF-8"));
}
return ret;
}
static void sendAll(OutputStream dst, InputStream src) throws Exception {
while(true) {
int v = src.read();
if (v == -1) { break; }
dst.write(v);
}
src.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment