๐ŸŒ web

๊ณ„์‚ฐ๊ธฐ ์›น ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ - request line

c0zi 2023. 9. 18. 01:19

์›น ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ ์ „, ํ”„๋กœํ† ์ฝœ ์š”์ฒญ์ด ์–ด๋–ป๊ฒŒ ๋“ค์–ด์˜ค๋Š” ์ง€ ์•Œ์•„๋ณด๊ณ  ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ๋™์ž‘์›๋ฆฌ๋ฅผ ์•Œ์•„๋ณด๋„๋ก ํ•œ๋‹ค.

 

requet line

 

GET /calculate?operand1=11&operator=*&operand2=55 HTTP/1.1

๋‹ค์Œ๊ณผ ๊ฐ™์€ ์š”์ฒญ์ด ๋“ค์–ด์˜ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋‹ค.

 

  • GET ์š”์ฒญ
  • Path Variable : /calculate
  • ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง : ?operand1=11&operator=*&operand2=55
  • ํ”„๋กœํ† ์ฝœ ๋ฐ ๋ฒ„์ „  : HTTP/1.1

 

Path variable๊ณผ ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์˜ ์ฐจ์ด์ ์— ๋Œ€ํ•ด์„œ๋Š” ์•„๋ž˜ ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•˜๋ฉด ์‰ฝ๊ฒŒ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

path์™€ ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์˜ ์ฐจ์ด ์•Œ์•„๋ณด๊ธฐ

 

zhdk์„œ๋ฒ„ ๋™์ž‘ ์˜ˆ์‹œ

 

๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„œ๋ฒ„๋ฅผ ๋™์ž‘์‹œ์ผฐ์„ ๋•Œ, request ์ฒซ๋ฒˆ์งธ ๋ผ์ธ(request)์„ splitํ•ด /calculate?operand1=11&operator=*&operand2=55 ์ด ๋ถ€๋ถ„์„ ์ถ”์ถœํ•œ๋‹ค.

 


RequestLine

 

๊ทธ๋ ‡๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ RequestLine์„ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ์„๊นŒ ?

๋จผ์ € split(" ")์„ ํ†ตํ•ด GET, url, ํ”„๋กœํ† ์ฝœ ๋ถ€๋ถ„์„ ๋‚˜๋ˆ„์–ด ์ค€ ๋‹ค.
๊ทธ๋ ‡๊ฒŒ ๋‚˜๋ˆˆ ์ฒซ๋ฒˆ์งธ ํ† ํฐ์„ method์— ์ €์žฅํ•˜๊ณ , ๋‘๋ฒˆ์งธ ํ† ํฐ์„ ?๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค๋ฉด path variable๋ถ€๋ถ„๊ณผ query string์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋‹ค.

์ด ๋•Œ, ์ฐธ๊ณ ๋กœ split ๋‚ด๋ถ€์— ?์™€ ๊ฐ™์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” split("\\?")์™€ ๊ฐ™์ด ์ ์–ด์ฃผ์–ด์•ผ ์˜ค๋ฅ˜๊ฐ€ ๋‚˜์ง€ ์•Š๋Š”๋‹ค. split("")์—์„œ ๋ฌธ์ž์—ด ๋ถ€๋ถ„์ด ์ •๊ทœํ‘œํ˜„์‹์„ ๋”ฐ๋ผ์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์ž์„ธํ•œ regex(์ •๊ทœํ‘œํ˜„์‹)์— ๋Œ€ํ•œ ์‚ฌํ•ญ์€ ๋‹ค์Œ ๋งํฌ๋ฅผ ํ†ตํ•ด ์•Œ ์ˆ˜ ์žˆ๋‹ค.

regex ๋” ์•Œ์•„๋ณด๊ธฐ

 

public RequestLine(String requestLine) {

    String[] tokens = requestLine.split(" ");
    this.method = tokens[0]; // GET

    String[] urlPathtokens = tokens[1].split("\\?");
    this.urlPath = urlPathtokens[0]; // /calculate

    // ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์ด ์žˆ๋Š” ๊ฒฝ์šฐ
    if (urlPathtokens.length == 2) {
        this.queryString = urlPathtokens[1]; // operand1=11&operator=*&operand2=55
    }
}

public RequestLine(String method, String urlPath, String queryString) {
    this.method = method;
    this.urlPath = urlPath;
    this.queryString = queryString;
}

 

๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋‘๊ฐœ์˜ ์ƒ์„ฑ์ž๋ฅผ ๋งŒ๋“ค์–ด ResquestLine์ด ์ •์ƒ์ ์œผ๋กœ ๋™์ž‘ํ•˜๋Š” ์ง€ test ํ•ด๋ณธ๋‹ค.

 

RequestLineTest

 

import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

public class RequestLineTest {
    @Test
    void create() {
        RequestLine requestLine = new RequestLine("GET /calculate?operand1=11&operator=*&operand2=55 HTTP/1.1");

        assertThat(requestLine).isNotNull();
        assertThat(requestLine).isEqualTo(new RequestLine("GET", "/calculate","operand1=11&operator=*&operand2=55"));
    }
}

 

๋‹ค์Œ์—๋Š” ์ด๋ ‡๊ฒŒ ๋ถ„๋ฆฌํ•œ Query String ์ค‘์—์„œ๋„ ๊ฐ key์™€ value๋“ค์„ ์ถ”์ถœํ•ด๋ณผ ์˜ˆ์ •์ด๋‹ค.