标题翻译
Is there anything in c similar to Reflection API and annotations are in java.?
问题
最近,我用C语言实现了一个HTTP服务器。在客户端请求它进行服务时,它能够很好地提供静态资源。现在我想让它像Java(Tomcat)中的JSP一样提供动态资源,也就是说,一些代码片段可以在服务器端执行,并且应该发送响应。我以前在Java中使用过反射、注解和其他核心库来做过类似的事情,但我以前从未在C中做过这样的事情。
有人可以指导我如何在C中实现这个吗?提前感谢。
英文翻译
Recently, I've implemented an HTTP Server in c language. it serves static resources very well when requesting client request it to serve. Now I want it to serve dynamic resources like jsp in java (tomcat), means some piece of code could execute at server side and response should be sent. I've done this kind of things in java using reflection, annotations and using other core libraries but I've never done this in c before.
Can someone guide me to do this in c.Thanks in advance.
答案1
得分: 0
没有等同于Reflection API或C中的Annotation的类似设施,但仍然可以实现您所需的功能,但需要进行一些繁重的工作。
主要是您想要:
-
弄清楚资源的类型是什么
-
根据类型,您想要使用一些脚本来执行它并发送其输出。
对于第一部分,您可以基于资源的扩展名来确定它。您可以使用系统的MIME类型,或者您可以创建自己的映射,就像这样:
struct Mapping {
char *extension;
char *command;
};
struct Mapping mapping[] = {
{"jsp", "<运行jsp的命令>"},
{"sh", "/bin/bash %1"},
};
对于第二部分,当您的服务器收到请求时,需要提取资源的扩展名,并在映射中查找与扩展名匹配的条目,获取command
字段,然后使用system()
调用执行该命令(如果有参数,需要进行替换)。
请注意,作为一个练习,这是学习很多东西的好方法,但如果将其投入生产,它将成为一个巨大的安全漏洞!
英文翻译
While there are no equivalent facilities similar to Reflection API or Annotation in C, it is still possible to implement what you require, but it will need you to do some heavy lifting.
Mainly what I am getting is that you want to:
-
Figure out what the type of the resource is
-
Depending on the type, you want to execute it with some script and send its output.
For part 1 you could base it on the extension of the resource. You could use system MIME types, or you could create your own mapping like this:
struct Mapping {
char *extension;
char *command;
};
struct Mapping mapping[] = {
{"jsp", "<command to run jsp>"},
{"sh", "/bin/bash %1"}
};
For part 2, when your server receives a request, it needs to extract the extension of the resource, and check in the mapping to see which entry matches the extension, obtain the command
field and execute the command (after substituting arguments if any) using system()
call.
Note that as an assignment this is a great way to learn a lot of things, but if you put this in production, it will be a huge security hole!
专注分享java语言的经验与见解,让所有开发者获益!
评论