Go: serving http directory with subdirectories

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

Go: serving http directory with subdirectories

问题

我有一个文件服务器层次结构:

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

我有两个位置用于静态文件,分别是 /tmp/core 和 /tmp/apps。
下面的代码可以工作,但是允许服务 /core 目录而不包括子目录。
为了服务于 /tmp/core/something 下的每个子目录,我需要为其指定 http.Handle。

有没有可能通过一个 http.Handle 的定义来更简单地指定它?

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

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/"))))

答案1

得分: 2

这个简单的代码片段用于提供我go文件夹及其内部的所有内容。

package main

import (
	"log"
	"net/http"
)

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

访问localhost:8080

这将提供我go文件夹中的文件以及所有子文件夹和文件。除非我误解了你的问题。

尝试运行上面的代码片段,并将路径设置为你驱动器上的一个文件夹。

英文:

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.

huangapple
  • 本文由 发表于 2014年7月19日 00:19:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/24829656.html
匿名

发表评论

匿名网友

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

确定