-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Day/20170406 #7
Open
MinKyoungSoo
wants to merge
3
commits into
slipp:master
Choose a base branch
from
MinKyoungSoo:day/20170406
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Day/20170406 #7
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
package webserver; | ||
|
||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import util.HttpRequestUtils; | ||
import util.IOUtils; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.io.InputStreamReader; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
|
||
public class HttpRequest { | ||
|
||
private static final Logger log = LoggerFactory.getLogger(RequestHandler.class); | ||
|
||
String httpMethod; | ||
String urlPath; | ||
|
||
HttpRequestHeader httpRequestHeader = new HttpRequestHeader(); | ||
Map<String, String> requestBody = new HashMap<>(); | ||
|
||
public HttpRequest(InputStream in) throws Exception { | ||
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); | ||
getRequestLine(br); | ||
getHeadersFromReader(br); | ||
getBodyFromReader(br); | ||
} | ||
|
||
private void getRequestLine(BufferedReader br) throws Exception { | ||
String line = br.readLine(); | ||
|
||
if(line == null) { | ||
throw new Exception("헤더정보를 만들수 없습니다."); | ||
} | ||
|
||
this.httpMethod = HttpRequestLine.getPath(line.split(" ")[0]); | ||
this.urlPath = HttpRequestLine.getPath(line.split(" ")[1]); | ||
} | ||
|
||
private void getHeadersFromReader(BufferedReader br) throws IOException { | ||
String line; | ||
while (!"".equals(line = br.readLine())) { | ||
httpRequestHeader.add(line); | ||
} | ||
} | ||
|
||
private void getBodyFromReader(BufferedReader br) throws IOException { | ||
if (Optional.ofNullable(this.getHeader("Content-Length")).isPresent()) { | ||
setRequestBody(br, Integer.parseInt(this.getHeader("Content-Length"))); | ||
} | ||
} | ||
|
||
private void setRequestBody(BufferedReader br, int contentLength) throws IOException { | ||
this.requestBody = HttpRequestUtils.parseQueryString(IOUtils.readData(br, contentLength)); | ||
} | ||
|
||
public String getHeader(String headerType) { | ||
return httpRequestHeader.getHeader(headerType); | ||
} | ||
|
||
public String getHttpMethod() { | ||
return this.httpMethod; | ||
} | ||
|
||
public String getPath() { | ||
return this.urlPath; | ||
} | ||
|
||
public Map<String, String> getRequestBodies() { | ||
return requestBody; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package webserver; | ||
|
||
import util.HttpRequestUtils; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
public class HttpRequestHeader { | ||
Map<String, String> requestHeaders = new HashMap<>(); | ||
|
||
public void add(String headerLine) { | ||
requestHeaders.put(HttpRequestUtils.parseHeader(headerLine).getKey(),HttpRequestUtils.parseHeader(headerLine).getValue()); | ||
} | ||
|
||
public String getHeader(String key) { | ||
return this.requestHeaders.get(key); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package webserver; | ||
|
||
public class HttpRequestLine { | ||
|
||
public static String getPath(String requestLine) { | ||
return requestLine.split(" ")[1]; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,25 @@ | ||
package webserver; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.DataOutputStream; | ||
import java.io.File; | ||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.io.InputStreamReader; | ||
import java.io.OutputStream; | ||
import java.net.Socket; | ||
import java.nio.file.Files; | ||
import java.util.ArrayList; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
|
||
import db.DataBase; | ||
import model.User; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import util.HttpRequestUtils; | ||
import util.IOUtils; | ||
|
||
public class RequestHandler extends Thread { | ||
private static final Logger log = LoggerFactory.getLogger(RequestHandler.class); | ||
|
@@ -23,16 +35,74 @@ public void run() { | |
connection.getPort()); | ||
|
||
try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) { | ||
|
||
HttpRequest httpRequest = new HttpRequest(in); | ||
|
||
String http_method = httpRequest.getHttpMethod(); | ||
String target_url = httpRequest.getPath(); | ||
|
||
// TODO 사용자 요청에 대한 처리는 이 곳에 구현하면 된다. | ||
DataOutputStream dos = new DataOutputStream(out); | ||
byte[] body = "Hello World".getBytes(); | ||
response200Header(dos, body.length); | ||
byte[] body = new byte[0]; | ||
|
||
if(target_url.equals("/user/create")) { | ||
addUserToDataBase(newUserFromParams(httpRequest.getRequestBodies())); | ||
response302Header(dos, "../../index.html"); | ||
} else if (http_method.equals("POST") && target_url.equals("/user/login")) { | ||
Map<String, String> userData = httpRequest.getRequestBodies(); | ||
if(isCorrectPassword(userData, findUserFromDataBase(userData.get("userId")))) { | ||
response302HeaderForCookie(dos, "../../index.html","logined=true"); | ||
} else { | ||
response302HeaderForCookie(dos, "./login_failed.html","logined=false"); | ||
} | ||
|
||
} else if(target_url.equals("/user/list")) { | ||
if(isLogined(httpRequest.getHeader("Cookie"))) { | ||
response302Header(dos, "./list.html"); | ||
} else { | ||
response302Header(dos, "./login.html"); | ||
} | ||
} else { | ||
body = Files.readAllBytes(new File("./webapp" + target_url).toPath()); | ||
|
||
if(target_url.contains(".css")) { | ||
response200HeaderForCss(dos, body.length); | ||
} else { | ||
response200Header(dos, body.length); | ||
} | ||
} | ||
|
||
responseBody(dos, body); | ||
} catch (IOException e) { | ||
} catch (Exception e) { | ||
log.error(e.getMessage()); | ||
} | ||
} | ||
|
||
private boolean isCorrectPassword(Map<String, String> params, User user) { | ||
return user.getPassword().equals(params.get("password")); | ||
} | ||
|
||
private boolean isLogined(String cookie) { | ||
return cookie.contains("logined=true"); | ||
} | ||
|
||
private void addUserToDataBase(User user) { | ||
DataBase.addUser(user); | ||
} | ||
|
||
private User findUserFromDataBase(String userId) { | ||
return DataBase.findUserById(userId); | ||
} | ||
|
||
private User newUserFromParams(Map<String, String> params) { | ||
return User.build( | ||
params.get("userId"), | ||
params.get("password"), | ||
params.get("name"), | ||
params.get("email") | ||
); | ||
} | ||
|
||
private void response200Header(DataOutputStream dos, int lengthOfBodyContent) { | ||
try { | ||
dos.writeBytes("HTTP/1.1 200 OK \r\n"); | ||
|
@@ -44,6 +114,38 @@ private void response200Header(DataOutputStream dos, int lengthOfBodyContent) { | |
} | ||
} | ||
|
||
private void response302Header(DataOutputStream dos, String redirectUrl) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 응답 처리하는 부분에 많은 중복 코드가 있는데요. |
||
try { | ||
dos.writeBytes("HTTP/1.1 302 Found\r\n"); | ||
dos.writeBytes(String.format("Location: %s\r\n", redirectUrl)); | ||
dos.writeBytes("\r\n"); | ||
} catch (IOException e) { | ||
log.error(e.getMessage()); | ||
} | ||
} | ||
|
||
private void response302HeaderForCookie(DataOutputStream dos, String redirectUrl, String cookie) { | ||
try { | ||
dos.writeBytes("HTTP/1.1 302 Found\r\n"); | ||
dos.writeBytes(String.format("Location: %s\r\n", redirectUrl)); | ||
dos.writeBytes("Set-Cookie: " + cookie + "\r\n"); | ||
dos.writeBytes("\r\n"); | ||
} catch (IOException e) { | ||
log.error(e.getMessage()); | ||
} | ||
} | ||
|
||
private void response200HeaderForCss(DataOutputStream dos, int lengthOfBodyContent) { | ||
try { | ||
dos.writeBytes("HTTP/1.1 200 OK \r\n"); | ||
dos.writeBytes("Content-Type: text/css;charset=utf-8\r\n"); | ||
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); | ||
dos.writeBytes("\r\n"); | ||
} catch (IOException e) { | ||
log.error(e.getMessage()); | ||
} | ||
} | ||
|
||
private void responseBody(DataOutputStream dos, byte[] body) { | ||
try { | ||
dos.write(body, 0, body.length); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package webserver; | ||
|
||
import org.junit.Test; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
|
||
public class HttpRequestHeaderTest { | ||
|
||
@Test | ||
public void getHeader() { | ||
HttpRequestHeader httpRequestHeader = new HttpRequestHeader(); | ||
httpRequestHeader.add("Connection : keep-alive"); | ||
assertEquals("keep-alive", httpRequestHeader.getHeader("Connection")); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package webserver; | ||
|
||
import org.junit.Test; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
|
||
public class HttpRequestLineTest { | ||
|
||
@Test | ||
public void getPath() { | ||
assertEquals("./index.html", HttpRequestLine.getPath("GET ./index.html")); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package webserver; | ||
|
||
import org.junit.Test; | ||
|
||
import static org.junit.Assert.*; | ||
|
||
public class HttpRequestTest { | ||
|
||
|
||
private String testDirectory = "./src/main/resources"; | ||
|
||
@Test | ||
public void 헤더를_통해_URI를_가져온다() { | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오호. 리팩토링 잘 하셨네요. 고민의 흔적이 느껴집니다.
어제 라이브 코딩에서 했듯이 이 각각의 method를 새로운 객체로 분리하는 시도를 해보시면 또 다른 재미를 느끼실 겁니다.