Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top