view src/luan/webserver/handlers/FileHandler.java @ 1167:7e6f28c769a1

better handlers
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 08 Feb 2018 19:06:31 -0700
parents 668f29bc52ea
children 312e4cadd508
line wrap: on
line source

package luan.webserver.handlers;

import java.io.File;
import java.io.FileInputStream;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import luan.webserver.Handler;
import luan.webserver.Request;
import luan.webserver.Response;
import luan.webserver.ResponseOutputStream;


public class FileHandler implements Handler {
	final File dir;

	public FileHandler() {
		this(".");
	}

	public FileHandler(String pathname) {
		this(new File(pathname));
	}

	public FileHandler(File dir) {
		if( !dir.isDirectory() )
			throw new RuntimeException("must be a directory");
		this.dir = dir;
	}

	public Response handle(Request request) {
		try {
			File file = new File(dir,request.path);
			return handle(request,file);
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
	}

	Response handle(Request request,File file) throws IOException {
		if( file.isFile() ) {
			Response response = new Response();
			response.body = new Response.Body( file.length(), new FileInputStream(file) );
			return response;
		}
		return null;
	}
}