Dmitry
Dmitry

Reputation: 1156

Go: serving http directory with subdirectories

I have file server hierarchy

/tmp/core/css/*.css 
/tmp/core/js/*.js 
/tmp/apps/someapp

I have two locations for static files /tmp/core and /tmp/apps accordingly. Following code works but allow to serve directory /core without subdirectories. To serve each subdirectory in /tmp/core/something I need to specify http.Handle for that.

Is it possible to specify it easier with one definition of http.Handle ?

http.Handle("/", http.FileServer(http.Dir("/tmp/apps/someapp"))) 
http.Handle("/core/", http.StripPrefix("/core/", http.FileServer(http.Dir("/tmp/static core/"))))

Upvotes: 0

Views: 3490

Answers (1)

sergserg
sergserg

Reputation: 22234

This simple snippet serves the contents of my go folder and everything within.

package main

import (
    "log"
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", http.FileServer(http.Dir("/Users/sergiotapia/go")))
}

Visit localhost:8080.

This serves my files in the go folder and every subdirectory and file within. Unless I'm misunderstanding your question.

Try running the snippet above and set the path to a folder on your drive.

Upvotes: 2

Related Questions