Add request inspection logic
This commit is contained in:
parent
ddab72b438
commit
6678825506
|
@ -10,6 +10,10 @@ public class Cobweb {
|
|||
try {
|
||||
CobwebServer srv = new CobwebServer(PORT, HOST);
|
||||
|
||||
srv.inspect("get", "/*", (req) -> {
|
||||
System.out.println(req.conn.ip + ":" + req.conn.port + " wants " + req.url());
|
||||
});
|
||||
|
||||
srv.on("get", "/hello/{?name}", (req) -> {
|
||||
if(req.params.length > 0) {
|
||||
return new HttpStaticResponse("Hello, " + req.params[0] + "!");
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
package com.spookyinternet.cobweb;
|
||||
|
||||
public class HttpConnection {
|
||||
public String ip;
|
||||
public int port;
|
||||
|
||||
public HttpConnection(String ip, int port) {
|
||||
this.ip = ip;
|
||||
this.port = port;
|
||||
}
|
||||
}
|
|
@ -4,14 +4,19 @@ import java.io.*;
|
|||
import java.util.*;
|
||||
|
||||
public class HttpRequest {
|
||||
public HttpConnection conn;
|
||||
public String method;
|
||||
public String path;
|
||||
public Map<String, String> headers;
|
||||
public String[] params;
|
||||
|
||||
public HttpRequest(BufferedReader reader) {
|
||||
public HttpRequest(BufferedReader reader, String ip, int port) {
|
||||
this.headers = new HashMap<String, String>();
|
||||
System.out.println(ip + "-" + port);
|
||||
HttpTokenStream tokens = new HttpTokenStream(reader);
|
||||
boolean processed = false;
|
||||
String header = null;
|
||||
StringBuilder value = new StringBuilder();
|
||||
|
||||
while(tokens.hasNext() && !processed) {
|
||||
HttpToken token = tokens.next();
|
||||
|
@ -20,9 +25,21 @@ public class HttpRequest {
|
|||
this.method = token.value.toLowerCase();
|
||||
} else if(token.line == 1 && token.seq == 3) {
|
||||
this.path = token.value;
|
||||
} else if(token.seq == 1 && token.value.endsWith(":")) {
|
||||
header = token.value.substring(0, token.value.length() - 1);
|
||||
} else if(token.eol && header != null) {
|
||||
this.headers.put(header.toLowerCase(), value.toString());
|
||||
header = null;
|
||||
value = new StringBuilder();
|
||||
} else if(header != null && token.seq > 2) {
|
||||
value.append(token.value);
|
||||
}
|
||||
|
||||
processed = token.value == "\r\n" && token.complete();
|
||||
}
|
||||
}
|
||||
|
||||
public String url() {
|
||||
return "http://" + this.headers.get("host") + this.path;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,7 +19,9 @@ public class HttpThread extends Thread {
|
|||
try {
|
||||
InputStream stream = this.sock.getInputStream();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
|
||||
HttpRequest req = new HttpRequest(reader);
|
||||
String ip = this.sock.getInetAddress().toString().substring(1);
|
||||
int port = this.sock.getPort();
|
||||
HttpRequest req = new HttpRequest(reader, ip, port);
|
||||
} catch(Exception err) {
|
||||
// :)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue