c - G-WAN handler重写方案

标签 c url-rewriting handler restful-url g-wan

这是我的脚本:

#include "gwan.h" // G-WAN exported functions
#include <string.h> // strstr()

int init(int argc, char *argv[])
{
    u32 *states = (u32*)get_env(argv, US_HANDLER_STATES);
    *states = 1 << HDL_AFTER_READ;
    return 0;
}

void clean(int argc, char *argv[])
{}

int main(int argc, char *argv[])
{
    if((long)argv[0] == HDL_AFTER_READ)
    {
        xbuf_t *read_xbuf = (xbuf_t*)get_env(argv, READ_XBUF);
        if(strstr(read_xbuf->ptr, "GET / HTTP/1.1"))
        {
            xbuf_repl(read_xbuf, "GET / HTTP/1.1", "GET /?index HTTP/1.1");
        }
        else
        {
            if(strstr(read_xbuf->ptr, ".c HTTP/1.1"))
            {
                int *pHTTP_status = (int*)get_env(argv, HTTP_CODE);
                if(pHTTP_status)
                    *pHTTP_status = 404;
                return 255;
            }
            xbuf_repl(read_xbuf, "GET /", "GET /?");
        }
    }
    return(255);
}

正如您可能理解的那样,我正在尝试将主页重定向到动态文件“hello.c”。 我还将每个请求重定向到动态目录(无需使用字符“?”),同时防止在 url 中使用扩展名“.c”。

此脚本部分有效,但显然会导致内存分配问题。 您有什么解决方案可以提出吗?

最佳答案

如果您担心性能,请不要使用 strstr。它将在整个请求中搜索匹配项。

根据您的脚本,您希望所有请求都是 GET,因此最好使用 strncmp,因为您只比较前 6 个字符。

int main(int argc, char *argv[])
{
    xbuf_t *read_xbuf = (xbuf_t*)get_env(argv, READ_XBUF);
    if(strncmp(read_xbuf->ptr, "GET / ", 6) == 0)
    {
        xbuf_repl(read_xbuf, " / ", " /?index ");
    }
    else
    {
        int pos = 5; // Start checking after '/' in "GET /"
        while(pos < 20) // Only check first 15 characters
        {               // Adjust depend on longest servlet name
            if(read_xbuf->ptr[pos] == '.' && read_xbuf->ptr[pos+1] == 'c')  // If request contains '.' return 404
            {
                int *pHTTP_status = (int*)get_env(argv, HTTP_CODE);
                if(pHTTP_status)
                    *pHTTP_status = 404;
                return 255;
            }
        }
        xbuf_repl(read_xbuf, "GET /", "GET /?");
    }
    return(255);
}

再次检查“.c”。您只想检查前 N 个字符。

如果你担心加'?'引起的内存分配问题对于您需要设计您的 servlet 名称的每个请求,以便可以进行就地替换。这是一个链接,其中包含有关如何实现就地替换以获得更好性能的示例。

RESTful URIs in G-WAN

我没有测试过上面的代码,所以它可能不起作用,但至少你会知道如何去做。此外,该脚本不处理流水线请求。

关于c - G-WAN handler重写方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15398849/

相关文章:

c++ - 如何以编程方式从 PKCS7 中提取 CA、多个 CA 和公共(public)证书/ key ?

apache - 重定向 CSS 过多

C 动态结构体的动态数组

c - dev-c++ 上的异常标识符或 '(' 之前的 'for'

url - 如何将我的 url 从 index.php 重写为 sample.php

android - Android 处理程序的使用

asp.net - 如何使用 asp.net 处理程序设置 html 正文背景图像?

perl - 如何判断两个句柄是否指向同一个文件

c - 文件指针在 while 循环的第二次迭代中变为 NULL

asp.net - 防止 IIS Url Rewrite 模块修改 HTTP 303/307 响应