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

huangapple go评论75阅读模式
英文:

Golang creating dynamic functions (during run time)

问题

我需要帮助你在Go语言中开发一个Web服务器。你从http://golang.org/doc/articles/wiki/上找到了一段初始代码,特别是这个例子:

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)
}

这段代码很简单,它的作用是将发送到"localhost"的GET请求重定向到handler函数,并输出HTML。

我遇到的问题是,在我的服务器中,我将在页面中使用JavaScript链接(特别是JQ和图像等)。所以当GET请求获取这些资源时,我需要将它们作为字节从驱动器中提取出来,并在handler中传递给客户端浏览器(就像上面的例子)。

**然而,在运行时之前,我不知道本地文件夹中有哪些文件,所以我无法预先创建这些处理程序。我想知道Go语言是否有一种在运行时动态创建函数的方法。**所以,我想的伪代码大致是这样的:

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

如果我可能走错了方向,如果有人有关于在读取文件后为这些本地文件创建处理程序的想法,请告诉我。我也不知道有多少文件或者有多少个,但我可以使用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!

答案1

得分: -2

正如@Not_a_Golfer所说,可以使用FileServer来处理静态文件。在我的情况下,这非常适用,因为我有很多未知的文件。

英文:

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.

huangapple
  • 本文由 发表于 2014年2月17日 00:03:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/21813648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定