首页
/ RoutingHTTPServer 技术文档

RoutingHTTPServer 技术文档

2024-12-24 19:03:04作者:江焘钦

本文档将详细介绍如何安装、使用以及通过API调用RoutingHTTPServer,这是一个基于CocoaHTTPServer的 Sinatra 风格路由API。

1. 安装指南

1.1 添加CocoaHTTPServer到项目

首先,您需要将CocoaHTTPServer添加到您的项目中。

1.2 添加源文件

然后,将Source目录下的文件添加到您的项目中。

2. 项目使用说明

以下是一个简单的例子,展示了如何初始化并使用RoutingHTTPServer:

http = [[RoutingHTTPServer alloc] init];
[http setPort:8000];
[http setDefaultHeader:@"Server" value:@"YourAwesomeApp/1.0"];

[http handleMethod:@"GET" withPath:@"/hello" block:^(RouteRequest *request, RouteResponse *response) {
    [response setHeader:@"Content-Type" value:@"text/plain"];
    [response respondWithString:@"Hello!"];
}];

您可以使用便捷方法处理GET/POST/PUT/DELETE请求:

[http get:@"/hello/:name" withBlock:^(RouteRequest *request, RouteResponse *response) {
    [response setHeader:@"Content-Type" value:@"text/plain"];
    [response respondWithString:[NSString stringWithFormat:@"Hello %@!", [request param:@"name"]]];
}];

在这个例子中,路径/hello/:name可以匹配/hello/world/hello/you等。路径中的命名参数会被添加到请求对象的params字典中,查询参数也会包含在这个字典里。

路径可以使用通配符:

[http get:@"/files/*.*" withBlock:^(RouteRequest *request, RouteResponse *response) {
    // "wildcards"参数是一个包含通配符匹配的NSArray
}];

或者您可以使用正则表达式(用花括号包裹):

[http get:@"{^/page/(\\d+)}" withBlock:^(RouteRequest *request, RouteResponse *response) {
    // "captures"参数是一个包含捕获组的NSArray
}];

路由也可以通过选择器处理:

- (void)setupRoutes {
    [http handleMethod:@"GET" withPath:@"/hello" target:self selector:@selector(handleHelloRequest:withResponse:)];
}

- (void)handleHelloRequest:(RouteRequest *)request withResponse:(RouteResponse *)response {
    [response respondWithString:@"Hello!"];
}

RouteResponses可以响应NSString或NSData对象、文件路径或现有的HTTPResponse类。响应也可以为空,只要设置了状态码或自定义头即可。例如,执行重定向:

[http get:@"/old" withBlock:^(RouteRequest *request, RouteResponse *response) {
    [response setStatusCode:302]; // 或 301
    [response setHeader:@"Location" value:[self.baseURL stringByAppendingString:@"/new"]];
}];

服务器对象还进行了以下增强:

  • 可以通过setDefaultHeader:value:或传递给setDefaultHeaders的字典设置默认头,允许您添加如Server头等信息。
  • 每个响应都会添加Connection头。如果您想在响应中显式设置,可以关闭持久连接。
  • 路由处理的调度队列可以更改。默认情况下,路由在CocoaHTTPServer的连接队列上处理,将其更改为dispatch_get_main_queue()将使所有路由在主线程上处理。连接处理仍在后台进行,只有路由处理器受到影响。

3. 项目API使用文档

RoutingHTTPServer提供了以下API供您使用:

  • + (instancetype)init: 初始化方法。
  • - (void)setPort:(NSInteger)port: 设置服务器端口号。
  • - (void)setDefaultHeader:(NSString *)header value:(NSString *)value: 设置默认响应头。
  • - (void)setDefaultHeaders:(NSDictionary *)headers: 设置默认响应头的字典。
  • - (void)handleMethod:(NSString *)method withPath:(NSString *)path block:(void (^)(RouteRequest *, RouteResponse *))block: 处理指定方法和路径的请求。
  • - (void)handleMethod:(NSString *)method withPath:(NSString *)path target:(id)target selector:(SEL)selector: 通过选择器处理指定方法和路径的请求。

更多API详情,请参考项目源码及文档。

4. 项目安装方式

请按照以下步骤安装RoutingHTTPServer:

  1. 将CocoaHTTPServer添加到您的项目中。
  2. Source目录下的文件添加到您的项目中。

完成以上步骤后,您就可以在项目中使用RoutingHTTPServer了。

登录后查看全文
热门项目推荐