Web applications 使用Gorilla toolkit使用根URL提供静态内容
我试图使用Gorilla工具包在Go web服务器中路由URL。作为指南,我有以下Go代码:Web applications 使用Gorilla toolkit使用根URL提供静态内容,web-applications,go,mux,Web Applications,Go,Mux,我试图使用Gorilla工具包在Go web服务器中路由URL。作为指南,我有以下Go代码: func main() { r := mux.NewRouter() r.Handle("/", http.FileServer(http.Dir("./static/"))) r.HandleFunc("/search/{searchTerm}", Search) r.HandleFunc("/load/{dataId}", Load) http.Handle(
func main() {
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./static/")))
r.HandleFunc("/search/{searchTerm}", Search)
r.HandleFunc("/load/{dataId}", Load)
http.Handle("/", r)
http.ListenAndServe(":8100", nil)
}
目录结构为:
...
main.go
static\
| index.html
| js\
| <js files>
| css\
| <css files>
当我访问http://localhost:8100
在我的web浏览器中,index.html
内容已成功交付,但是,所有js
和css
URL返回404
如何让程序从静态
子目录中提供文件?试试以下方法:
fileHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("/absolute/path/static")))
http.Handle("/static/", fileHandler)
我想您可能正在寻找
PathPrefix
func main() {
r := mux.NewRouter()
r.HandleFunc("/search/{searchTerm}", Search)
r.HandleFunc("/load/{dataId}", Load)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
http.ListenAndServe(":8100", r)
}
经过反复试验,以上两个答案都帮助我找到了适合我的答案。我在web应用的根目录中有一个静态文件夹 除了
PathPrefix
之外,我还必须使用StripPrefix
来递归地获取路径
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
r.PathPrefix("/static/").Handler(s)
http.Handle("/", r)
err := http.ListenAndServe(":8081", nil)
}
我希望它能帮助其他有问题的人。我这里有这段代码,它工作得很好,并且可以重用
func ServeStatic(router *mux.Router, staticDirectory string) {
staticPaths := map[string]string{
"styles": staticDirectory + "/styles/",
"bower_components": staticDirectory + "/bower_components/",
"images": staticDirectory + "/images/",
"scripts": staticDirectory + "/scripts/",
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir(pathValue))))
}
}
router := mux.NewRouter()
ServeStatic(router, "/static/")
这将为文件夹标志内的所有文件提供服务,并在根目录下提供index.html 用法 代码
这意味着将所有
src
,href
等属性更改为“/static/js/jquery.min.js”
。虽然从技术上讲可以工作。这将允许加载JS和CSS文件,但是index.html
文件将不再在http://localhost:8100/
我通常把所有的图像
,css
,js
etc在static
文件夹中。主页的内容通常是动态生成的。如果主页通过JavaScript获取所有动态内容,则index.html本身通常是完全静态的。您可能希望看到此讨论(但不使用Gorilla)关于从root或subdirectories@Ripounet提供静态文件,我在研究过程中确实看到了这个问题,但是,由于它没有使用Gorilla,我始终无法想到如何使用我的设置,我的目标之一是在我的项目的根目录中没有任何静态文件(位于main.go
)。另外,它似乎与下面的非常相似,这也将不适用于我的设置。这很有帮助,谢谢。不过,我在尝试使用两个别名时遇到了问题。例如r.PathPrefix(“/a/”).Handler(http.FileServer(http.Dir(“b/”)))r.PathPrefix(“/”).Handler(http.FileServer(http.Dir(“c/”))))
在这种情况下,c/
中的所有内容都提供了服务,但不提供b/
。尝试了一些不同的细微变化,但没有成功。有什么想法吗?@markdsievers,您可能需要从URL中删除“/a/”部分。示例:r.PathPrefix(“/a/”).Handler(http.StripPrefix(“/a/”),http.FileServer(http.Dir(“b”))
。是否可以添加NotFound处理程序?代码似乎与我当前的项目代码类似,只是需要注意:静态处理程序需要作为最后一个路由放置,否则,其他
路由的GET也将被该静态处理程序覆盖。这为我修复了它!正如@HoangTran所提到的,您需要将此设置为最后一条路线。基本上,如果所有其他操作都失败了,则类似于“一网打尽”。对于使用s:=…
的任何人,当您的工作目录为[workspace]/src
时,应阅读如下内容s:=http.StripPrefix(“/static/”),httpFileServer(http.Dir(“/web/static/”)
我想,您也可以使用一些“github.com/lpar/gZip”或类似的库来gZip静态内容gzip.FileServer(http.Dir(“./static/”)
它对我不起作用,我找不到404页
func ServeStatic(router *mux.Router, staticDirectory string) {
staticPaths := map[string]string{
"styles": staticDirectory + "/styles/",
"bower_components": staticDirectory + "/bower_components/",
"images": staticDirectory + "/images/",
"scripts": staticDirectory + "/scripts/",
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir(pathValue))))
}
}
router := mux.NewRouter()
ServeStatic(router, "/static/")
//port default values is 8500
//folder defaults to the current directory
go run main.go
//your case, dont forget the last slash
go run main.go -folder static/
//dont
go run main.go -folder ./
package main
import (
"flag"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/kr/fs"
)
func main() {
mux := mux.NewRouter()
var port int
var folder string
flag.IntVar(&port, "port", 8500, "help message for port")
flag.StringVar(&folder, "folder", "", "help message for folder")
flag.Parse()
walker := fs.Walk("./" + folder)
for walker.Step() {
var www string
if err := walker.Err(); err != nil {
fmt.Fprintln(os.Stderr, "eroooooo")
continue
}
www = walker.Path()
if info, err := os.Stat(www); err == nil && !info.IsDir() {
mux.HandleFunc("/"+strings.Replace(www, folder, "", -1), func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, www)
})
}
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, folder+"index.html")
})
http.ListenAndServe(":"+strconv.Itoa(port), handlers.LoggingHandler(os.Stdout, mux))
}