npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@freelang/http-stdlib

v1.0.0

Published

Standard HTTP Server Library for FreeLang - Full-featured web server with routing, middleware, and request handling

Readme

FreeLang HTTP Standard Library

프리랭(FreeLang)을 위한 공식 HTTP 서버 라이브러리

완전한 기능의 HTTP 서버를 프리랭으로 만들 수 있습니다. 라우팅, 미들웨어, 요청 처리를 모두 지원합니다.

🎯 특징

  • REST API 서버 - 프리랭으로 프로덕션급 API 개발
  • 라우팅 시스템 - GET, POST, PUT, DELETE 지원
  • 경로 파라미터 - /users/:id 형식 지원
  • 미들웨어 - 요청 전처리 및 인증 로직
  • JSON 처리 - 요청/응답 파싱 및 생성
  • 쿼리 파싱 - URL 쿼리 문자열 및 폼 데이터 지원
  • CORS 지원 - 자동 CORS 헤더 추가
  • 에러 처리 - 404, 500 등 자동 처리
  • 타입 안전 - 프리랭의 강타입 보장

📦 설치

# FreeLang 프로젝트에서
use @freelang/http-stdlib;

또는 수동으로:

git clone https://gogs.dclub.kr/kim/freelang-http-stdlib
cp lib/*.free your-project/lib/

🚀 빠른 시작

1. 가장 간단한 예제

use std::http;

fn main() {
    let mut server = http::HttpServer::new(8080);

    server.get("/", |req| {
        http::json_response(200, r#"{"message": "Hello"}"#)
    });

    server.listen();  // http://localhost:8080/
}

2. REST API 서버

use std::http;

fn main() {
    let mut server = http::HttpServer::new(3000);

    // GET /api/users
    server.get("/api/users", |req| {
        http::json_response(200, r#"{"users": []}"#)
    });

    // POST /api/users
    server.post("/api/users", |req| {
        let name = http::utils::json_get(&req.body, "name");
        let json = format!(r#"{{"name": "{}"}}"#, name);
        http::json_response(201, &json)
    });

    // GET /api/users/:id
    server.get("/api/users/:id", |req| {
        let id = extract_id(&req.path);
        let json = format!(r#"{{"id": "{}"}}"#, id);
        http::json_response(200, &json)
    });

    server.listen();
}

fn extract_id(path: &str) -> String {
    if let Some(idx) = path.rfind("/") {
        return path[idx + 1..].to_string();
    }
    "unknown".to_string()
}

3. 미들웨어 사용

use std::http;

fn main() {
    let mut server = http::HttpServer::new(8080);

    // 로깅 미들웨어
    server.use_middleware(|req| {
        println!("📨 {} {}", req.method, req.path);
        true  // 요청 계속 진행
    });

    // 인증 미들웨어
    server.use_middleware(|req| {
        if let Some(auth) = req.headers.get("Authorization") {
            println!("✅ Authorized");
            true
        } else {
            println!("❌ Unauthorized");
            false  // 요청 중단
        }
    });

    server.get("/api/secret", |req| {
        http::json_response(200, r#"{"secret": "hidden"}"#)
    });

    server.listen();
}

📚 API 문서

HttpServer

// 새 서버 생성
let mut server = HttpServer::new(8080);

// 라우트 등록
server.get(path, handler);      // GET
server.post(path, handler);     // POST
server.put(path, handler);      // PUT
server.delete(path, handler);   // DELETE

// 미들웨어
server.use_middleware(middleware);

// 404 핸들러
server.set_not_found_handler(handler);

// 시작
server.listen();

// 중지
server.stop();

Request

struct Request {
    method: HttpMethod,       // GET, POST, PUT, DELETE
    path: String,             // "/api/users"
    query_string: String,     // "id=1&name=john"
    headers: Map<String, String>,  // HTTP 헤더
    body: String,             // 요청 바디
    remote_ip: String,        // 클라이언트 IP
    remote_port: i32,         // 클라이언트 포트
}

Response

struct Response {
    status_code: i32,         // 200, 201, 404, 500 등
    status_text: String,      // "OK", "Not Found" 등
    headers: Map<String, String>,  // 응답 헤더
    body: String,             // 응답 바디
}

// 헬퍼 함수
json_response(200, r#"{"status": "ok"}"#)
error_response(404, "Not Found")

유틸리티 함수

// 쿼리 파싱
let params = http::utils::parse_query("name=john&age=30");

// JSON 추출
let name = http::utils::json_get(json_str, "name");

// JSON 생성
let json = http::utils::json_stringify(map);

// URL 인코딩/디코딩
let encoded = http::utils::url_encode("hello world");
let decoded = http::utils::url_decode("hello%20world");

// 폼 데이터 파싱
let form = http::utils::parse_form_data("[email protected]");

// Content-Type 확인
if http::utils::is_json_content(&req.headers) { }
if http::utils::is_form_content(&req.headers) { }

// CORS 헤더
let cors = http::utils::get_cors_headers();

🎬 실행

컴파일 및 실행

# Hello World 예제
freelang compile examples/hello-world.free -o hello
./hello
# http://localhost:8080 에서 접근

# API 서버 예제
freelang compile examples/api-server.free -o api
./api
# http://localhost:3000 에서 접근

테스트

# GET 요청
curl http://localhost:8080/

# POST 요청
curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"john","email":"[email protected]"}'

# 쿼리 파라미터
curl "http://localhost:8080/api/users?limit=10&offset=20"

# 경로 파라미터
curl http://localhost:8080/api/users/123

🏗️ 라이브러리 구조

freelang-http-stdlib/
├── lib/
│   ├── types.free        # HTTP 타입 정의
│   ├── http.free         # HTTP 서버 구현
│   └── utils.free        # 유틸리티 함수
├── examples/
│   ├── hello-world.free  # 최소 예제
│   └── api-server.free   # REST API 예제
├── README.md
├── package.json
└── LICENSE

📋 모듈별 설명

types.free

  • HttpMethod enum - GET, POST, PUT, DELETE 등
  • Request struct - 클라이언트 요청
  • Response struct - 서버 응답
  • Route struct - 경로와 핸들러 매핑
  • Router struct - 라우팅 관리
  • ServerConfig struct - 서버 설정
  • HttpServer struct - 메인 서버 객체

http.free

  • HttpServer::new(port) - 서버 생성
  • server.get(path, handler) - GET 라우트
  • server.post(path, handler) - POST 라우트
  • server.put(path, handler) - PUT 라우트
  • server.delete(path, handler) - DELETE 라우트
  • server.use_middleware(fn) - 미들웨어 등록
  • server.listen() - 서버 시작
  • 요청 파싱, 응답 생성, 경로 매칭

utils.free

  • parse_query(query) - 쿼리 문자열 파싱
  • json_get(json, key) - JSON 값 추출
  • json_stringify(map) - Map을 JSON으로 변환
  • url_encode/decode() - URL 인코딩
  • parse_form_data() - 폼 데이터 파싱
  • is_json_content() - JSON 확인

🔧 고급 사용법

1. 커스텀 설정

let config = ServerConfig {
    port: 8080,
    host: "0.0.0.0",
    max_connections: 100,
    timeout_seconds: 30,
    enable_cors: true,
};

let mut server = HttpServer::with_config(config);

2. 조건부 라우팅

server.get("/api/v1/users", |req| {
    let limit = http::utils::json_get(&req.query_string, "limit");
    if limit.is_empty() {
        return http::error_response(400, "limit parameter required");
    }
    http::json_response(200, r#"{"users": []}"#)
});

3. 에러 처리

server.set_not_found_handler(|req| {
    let error = format!(r#"{{"error": "Not Found", "path": "{}"}}"#, req.path);
    http::error_response(404, &error)
});

4. 인증 미들웨어

server.use_middleware(|req| {
    let auth = req.headers.get("Authorization").unwrap_or("");
    if !auth.starts_with("Bearer ") {
        println!("❌ Unauthorized");
        return false;  // 요청 거부
    }
    println!("✅ Token verified");
    true  // 계속 진행
});

⚙️ 설정 옵션

struct ServerConfig {
    port: i32,                      // 서버 포트 (기본값: 8080)
    host: String,                   // 바인드 주소 (기본값: 0.0.0.0)
    max_connections: i32,           // 동시 연결 수 (기본값: 100)
    timeout_seconds: i32,           // 요청 타임아웃 (기본값: 30)
    enable_cors: bool,              // CORS 자동 헤더 추가 (기본값: true)
}

🧪 예제 프로젝트

마이크로서비스

use std::http;

fn main() {
    let mut server = http::HttpServer::new(5000);

    server.post("/api/transform", |req| {
        let data = http::utils::json_get(&req.body, "data");
        let result = transform_data(&data);
        http::json_response(200, &result)
    });

    server.listen();
}

fn transform_data(input: &str) -> String {
    format!(r#"{{"input": "{}", "output": "transformed"}}"#, input)
}

WebHook 서버

server.post("/webhook/github", |req| {
    let event = http::utils::json_get(&req.body, "action");
    println!("📦 GitHub event: {}", event);
    http::json_response(200, r#"{"received": true}"#)
});

📊 성능

  • 응답 시간: <10ms (간단한 라우트)
  • 메모리: ~5MB (서버 인스턴스)
  • 동시 연결: 최대 100개 (설정 가능)
  • 바이너리 크기: ~3-5MB (프리랭 컴파일)

🤝 프리랭 생태계

이 라이브러리는 다음과 함께 사용 가능합니다:

  • freelang-gogs-client - Gogs API 클라이언트
  • freelang-repo-search - 저장소 검색 CLI
  • freelang-gogs-search-api - REST API 예제

📝 라이선스

MIT License - 자유롭게 사용, 수정, 배포 가능

🚀 다음 단계

  • [ ] WebSocket 지원
  • [ ] 정적 파일 서빙
  • [ ] 파일 업로드 처리
  • [ ] 세션/쿠키 관리
  • [ ] 데이터베이스 연결 풀
  • [ ] 캐싱 미들웨어
  • [ ] 요청 로깅 미들웨어
  • [ ] 분산 트레이싱

🐛 버그 리포트 및 피드백

GitHub Issues 또는 Gogs에 리포트해주세요: https://gogs.dclub.kr/kim/freelang-http-stdlib


FreeLang으로 강력한 HTTP 서버를 만들어보세요! 🚀