Golang创建动态函数(在运行期间)

Golang创建动态函数(在运行期间)

问题描述:

I need some help developing a web server in go. I took initial code from http://golang.org/doc/articles/wiki/ , in particular, this example :

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

This code is pretty simple to follow as all it does is redirect a get request going to "localhost" to the handler function which outputs html.

The problem I am having is that with my server I will be using javascript linkage in my pages (particularly JQ, and images, etc). So when a GET request comes in for those artifacts I need to pull them from the drive as bytes and give them to the client browser in the handler (like above).

However; before run time I have no idea which files are located in local folders so I cannot pre-make these handlers. I was wondering if go had a way to dynamically make functions during run time. So the psuedocode I'm thinking of would go something like this:

for file in files:
    http.HandleFunc(file.location, handler)

If maybe I'm going about this the wrong way and if anyone has ideas on creating handlers for these local files after reading them please let me know. I also do not have any idea of the amount of files or how many but I can use Golang to read all the files.

Thanks!

我需要一些帮助来开发Web服务器。 我从 http://golang.org/doc/articles/wiki/ 中获取了初始代码, 特别是这个示例: p>

  func handler(w http.ResponseWriter,r * http.Request){
 fmt.Fprintf(w,“嗨,我爱%  s!“,r.URL.Path [1:])
} 
 
func main(){
 http.HandleFunc(” /“,handler)
 http.ListenAndServe(”:8080“,nil)  
} 
  code>  pre> 
 
 

此代码非常简单,因为它所做的只是将获取请求重定向到“ localhost”到输出html的处理函数。 / p>

我遇到的问题是,在服务器上,我将在页面中使用javascript链接(尤其是JQ和图像等)。 因此,当收到针对这些工件的GET请求时,我需要将它们作为字节从驱动器中拉出,并将它们提供给处理程序中的客户端浏览器(如上)。 p>

; 在运行时之前,我不知道哪些文件位于本地文件夹中,因此无法预先制作这些处理程序。 我想知道go是否有办法在运行时动态创建函数。 strong>所以我正在考虑的伪代码会像这样: p>

 用于文件 在文件中:
 http.HandleFunc(file.location,handler)
  code>  pre> 
 
 

如果我可能会以错误的方式进行操作,并且有人对创建 阅读这些本地文件的处理程序后,请告诉我。 我也不知道文件的数量或多少,但是我可以使用Golang读取所有文件。 p>

谢谢! p> div>

as @Not_a_Golfer stated ; this can be done with FileServer for static files. In my situation this works quite well as I have numerous unknown files.