在Golang中,如何在根目录之外提供静态内容,同时仍然有一个根目录处理程序来为主页提供服务。
以以下简单的web服务器为例:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", HomeHandler) // homepage
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "HomeHandler")
}如果我这样做了
http.Handle("/", http.FileServer(http.Dir("./")))我收到一个恐慌,说我有两个"/“的注册。我在互联网上找到的每一个Golang示例都建议从不同的目录中提供静态内容,但这对sitemap.xml、favicon.ico、robots.txt和其他文件没有太大帮助,这些文件通常是通过实践或强制总是从根目录提供的。
我寻找的行为是在大多数web服务器中都可以找到的行为,比如Apache,Nginx或IIS,它首先遍历你的规则,如果没有找到规则,它会查找实际的文件,如果没有找到文件,它会查找404s。我的猜测是,我需要编写一个http.HandlerFunc来检查我是否引用了一个带有扩展名的文件,如果是,则检查文件是否存在并服务于该文件,否则它将404s或服务于主页是对"/“的请求。不幸的是,我甚至不确定如何开始这样的任务。
我的一部分是说我把情况变得过于复杂了,这让我觉得我错过了什么?任何指导都将不胜感激。
发布于 2012-12-30 06:41:57
我想到的一件事可能会对你有所帮助,那就是你可以创建自己的ServeMux。我在您的示例中添加了chttp,以便您可以使用ServeMux来服务静态文件。然后,HomeHandler检查它是否应该提供文件。我只是检查一个".“但是你可以做很多事情。这只是一个想法,可能不是你想要的。
package main
import (
"fmt"
"net/http"
"strings"
)
var chttp = http.NewServeMux()
func main() {
chttp.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/", HomeHandler) // homepage
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if (strings.Contains(r.URL.Path, ".")) {
chttp.ServeHTTP(w, r)
} else {
fmt.Fprintf(w, "HomeHandler")
}
} 发布于 2013-01-07 07:29:27
另一种(不使用ServeMux)解决方案是显式地为根目录中的每个文件提供服务。其背后的想法是使基于root的文件数量非常少。sitemap.xml、favicon.ico、robots.txt确实被要求从根目录提供服务:
package main
import (
"fmt"
"net/http"
)
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "HomeHandler")
}
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
func main() {
http.HandleFunc("/", HomeHandler) // homepage
// Mandatory root-based resources
serveSingle("/sitemap.xml", "./sitemap.xml")
serveSingle("/favicon.ico", "./favicon.ico")
serveSingle("/robots.txt", "./robots.txt")
// Normal resources
http.Handle("/static", http.FileServer(http.Dir("./static/")))
http.ListenAndServe(":8080", nil)
}请移动所有其他资源(CSS、JS等)到适当的子目录,例如/static/。
发布于 2013-10-17 07:06:59
使用Gorilla mux package:
r := mux.NewRouter()
//put your regular handlers here
//then comes root handler
r.HandleFunc("/", homePageHandler)
//if a path not found until now, e.g. "/image/tiny.png"
//this will look at "./public/image/tiny.png" at filesystem
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)https://stackoverflow.com/questions/14086063
复制相似问题