Skip to content

Instantly share code, notes, and snippets.

@paulocoutinhox
Created July 19, 2023 03:29
Show Gist options
  • Save paulocoutinhox/a3c1e818320a2e56056726ee7c8dc555 to your computer and use it in GitHub Desktop.
Save paulocoutinhox/a3c1e818320a2e56056726ee7c8dc555 to your computer and use it in GitHub Desktop.
Java NanoHTTP WebServer
package server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import fi.iki.elonen.NanoHTTPD;
public class WebServer extends NanoHTTPD {
private static final int PORT = 8080;
private static final String DEFAULT_FILE = "index.html";
private String staticFolder;
public WebServer(String staticFolder) throws IOException {
super(PORT);
this.staticFolder = staticFolder;
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
@Override
public Response serve(IHTTPSession session) {
String uri = session.getUri();
String filePath;
if (uri.equals("/")) {
filePath = staticFolder + "/" + DEFAULT_FILE;
} else {
filePath = staticFolder + uri;
}
try {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
InputStream inputStream = new FileInputStream(file);
Response response = newFixedLengthResponse(Response.Status.OK, getMimeType(filePath), inputStream, file.length());
/*
response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "0");
*/
return response;
} else {
return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Arquivo não encontrado");
}
} catch (IOException e) {
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "Erro ao processar a requisição");
}
}
private String getMimeType(String filePath) {
String mimeType = NanoHTTPD.getMimeTypeForFile(filePath);
if (mimeType == null) {
mimeType = NanoHTTPD.MIME_PLAINTEXT;
}
return mimeType;
}
}
/*
Usage:
WebServer server = new WebServer("/data/data/PACKAGE/www");
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment