面试题答案
一键面试#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_REQUEST_LENGTH 1024
typedef struct {
char method[10];
char path[MAX_REQUEST_LENGTH];
} HttpRequest;
int parseHttpRequest(const char *request, HttpRequest *httpRequest) {
const char *start = request;
const char *end;
// 提取请求方法
end = strchr(start,'');
if (end == NULL) {
return -1; // 格式错误,没有找到请求方法后的空格
}
strncpy(httpRequest->method, start, end - start);
httpRequest->method[end - start] = '\0';
// 跳过空格
start = end + 1;
// 提取请求路径
end = strchr(start,'');
if (end == NULL) {
return -2; // 格式错误,没有找到请求路径后的空格
}
strncpy(httpRequest->path, start, end - start);
httpRequest->path[end - start] = '\0';
return 0;
}
你可以使用以下方式调用这个函数:
int main() {
char request[MAX_REQUEST_LENGTH] = "GET /index.html HTTP/1.1";
HttpRequest httpRequest;
int result = parseHttpRequest(request, &httpRequest);
if (result == 0) {
printf("Method: %s\n", httpRequest.method);
printf("Path: %s\n", httpRequest.path);
} else if (result == -1) {
printf("HTTP request format error: cannot find space after method\n");
} else if (result == -2) {
printf("HTTP request format error: cannot find space after path\n");
}
return 0;
}