본문 바로가기
Dart/Dart Server

[초급] Dart로 간단한 서버 구축하기/라우팅 기초: 경로에 따른 요청 처리

by Maccrey Coding 2024. 9. 5.
반응형

 

1. 개요

라우팅은 클라이언트의 요청 URL 경로에 따라 서버에서 적절한 핸들러를 호출하는 과정입니다.

Dart에서는 기본적으로 dart:io 라이브러리를 사용하여 직접 라우팅 로직을 구현할 수 있습니다.

이 포스트에서는 경로에 따른 요청 처리 방법을 단계별로 설명합니다.

2. 기본 라우팅 설정

2.1. 프로젝트 설정

새 Dart 프로젝트를 생성하거나 기존 프로젝트를 사용하여 다음 파일을 설정합니다.

  • lib/server.dart

2.2. 라우팅 코드 작성

server.dart 파일에 다음 코드를 작성하여 기본적인 라우팅을 구현합니다.

import 'dart:convert'; // JSON 디코딩을 위해 필요
import 'dart:io';

void main() async {
  final address = InternetAddress.loopbackIPv4;
  final port = 8080;

  final server = await HttpServer.bind(address, port);
  print('Listening on http://${address.host}:$port/');

  await for (HttpRequest request in server) {
    // 요청 경로에 따라 라우팅
    final path = request.uri.path;

    if (path == '/') {
      handleRootRequest(request);
    } else if (path == '/about') {
      handleAboutRequest(request);
    } else if (path == '/contact') {
      handleContactRequest(request);
    } else {
      handleNotFoundRequest(request);
    }
  }
}

// 루트 경로 처리
void handleRootRequest(HttpRequest request) {
  request.response
    ..statusCode = HttpStatus.ok
    ..headers.contentType = ContentType.text
    ..write('Welcome to the Dart HTTP Server!')
    ..close();
}

// About 경로 처리
void handleAboutRequest(HttpRequest request) {
  request.response
    ..statusCode = HttpStatus.ok
    ..headers.contentType = ContentType.text
    ..write('This is the About page.')
    ..close();
}

// Contact 경로 처리
void handleContactRequest(HttpRequest request) {
  request.response
    ..statusCode = HttpStatus.ok
    ..headers.contentType = ContentType.text
    ..write('This is the Contact page.')
    ..close();
}

// 404 Not Found 경로 처리
void handleNotFoundRequest(HttpRequest request) {
  request.response
    ..statusCode = HttpStatus.notFound
    ..headers.contentType = ContentType.text
    ..write('404 Not Found')
    ..close();
}

3. 코드 설명

  • 서버 설정: HttpServer.bind 메서드를 사용하여 서버를 시작하고, IP와 포트를 설정합니다.
  • 요청 처리: await for (HttpRequest request in server)를 사용하여 클라이언트의 요청을 비동기적으로 처리합니다.
  • 라우팅 로직
    • 요청의 경로(request.uri.path)에 따라 적절한 핸들러 메서드를 호출합니다.
    • 각 경로에 대해 별도의 메서드를 정의하여 응답을 설정합니다.
    • 정의되지 않은 경로에 대해 404 Not Found 응답을 보냅니다.

4. 서버 실행 및 테스트

서버를 실행하려면 터미널에서 다음 명령어를 입력합니다.

dart run lib/server.dart

서버가 실행되면 다음 경로를 웹 브라우저에서 테스트할 수 있습니다

  • 루트 경로: http://localhost:8080/ — "Welcome to the Dart HTTP Server!"
  • About 경로: http://localhost:8080/about — "This is the About page."
  • Contact 경로: http://localhost:8080/contact — "This is the Contact page."
  • 기타 경로: 예를 들어, http://localhost:8080/unknown — "404 Not Found"

5. 동적 라우팅 구현 (선택 사항)

동적 경로를 처리하여 변수로 요청 경로를 받을 수도 있습니다. 예를 들어, /user/{id}와 같은 경로를 처리할 수 있습니다. 다음 예제는 동적 경로를 처리하는 방법을 보여줍니다.

void handleDynamicRequest(HttpRequest request) {
  final path = request.uri.path;
  final segments = path.split('/');

  if (segments.length == 3 && segments[1] == 'user') {
    final userId = segments[2];
    request.response
      ..statusCode = HttpStatus.ok
      ..headers.contentType = ContentType.text
      ..write('User ID: $userId')
      ..close();
  } else {
    handleNotFoundRequest(request);
  }
}

이 코드는 /user/{id}와 같은 경로를 처리하고, {id} 부분을 변수로 받아서 응답을 생성합니다.

6. 요약

  • 라우팅 설정: 요청 경로에 따라 다른 핸들러를 호출하여 적절한 응답을 생성합니다.
  • 기본 라우팅: 각 경로에 대해 별도의 메서드를 정의하고, 요청에 따라 호출합니다.
  • 동적 라우팅: 요청 경로의 변수 부분을 처리하여 동적인 응답을 생성할 수 있습니다.

이 포스트가 Dart에서 HTTP 서버의 라우팅을 설정하고 경로에 따라 요청을 처리하는 데 도움이 되기를 바랍니다. Dart의 dart:io 라이브러리를 사용하여 다양한 라우팅 로직을 구현할 수 있습니다.

구독!! 공감과 댓글은 저에게 큰 힘이 됩니다.

Starting Google Play App Distribution! "Tester Share" for Recruiting 20 Testers for a Closed Test.

 

Tester Share [테스터쉐어] - Google Play 앱

Tester Share로 Google Play 앱 등록을 단순화하세요.

play.google.com

반응형