The Go standard package allows us to easily serve a certain directory in the filesystem, using the net.FileServer function, which, when given the net.FileSystem interface, returns a Handler that serves that directory. The default implementation is net.Dir , which is a custom string that represents a directory in the system. The FileServer function already has a protection mechanism that prevents us to use a relative path, such as../../../dir, to access directories outside the served one.
The following is a sample file server that uses the directory provided as an argument, as the root of the file served:
func main() {
if len(os.Args) != 2 {
log.Fatalln("Please specify a directory")
}
s, err := os.Stat(os.Args[1])
if err == nil && !s.IsDir() {
err = errors.New("not a directory")
}
if err != nil {
log.Fatalln("Invalid path:", err)
}
http.Handle("/", http.FileServer(http.Dir(os.Args[1])))
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal(err)
}
}