使用Gorilla工具包为根URL提供静态内容

jas*_*son 55 web-applications go mux

我试图使用Gorilla工具包的mux来路由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("/", r)
    http.ListenAndServe(":8100", nil)
}
Run Code Online (Sandbox Code Playgroud)

目录结构是:

...
main.go
static\
  | index.html
  | js\
     | <js files>
  | css\
     | <css files>
Run Code Online (Sandbox Code Playgroud)

Javascript和CSS文件的引用方式index.html如下:

...
<link rel="stylesheet" href="css/redmond/jquery-ui.min.css"/>
<script src="js/jquery.min.js"></script>
...
Run Code Online (Sandbox Code Playgroud)

当我http://localhost:8100在我的Web浏览器中访问index.html内容成功传递时,所有jscssURL都返回404.

如何让程序从static子目录中提供文件?

Chr*_*loe 80

我想你可能在寻找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)
}
Run Code Online (Sandbox Code Playgroud)

  • @markdsievers,您可能需要从URL中删除"/ a /"部分.示例:`r.PathPrefix("/ a /").处理程序(http.StripPrefix("/ a /",http.FileServer(http.Dir("b"))))`. (3认同)
  • 该代码似乎与我当前的项目代码类似,只是需要注意:静态处理程序需要作为最后一个路由,否则“其他”路由的 GET 也将被该静态处理程序覆盖。 (2认同)

cod*_*eak 40

经过大量的反复试验,上述两个答案都帮助我找到了对我有用的东西.我在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)
}
Run Code Online (Sandbox Code Playgroud)

我希望它可以帮助别人遇到问题.

  • 这是唯一对我有用的答案. (11认同)

Tho*_*eis 9

我在这里有这个代码非常好用并且可以重复使用.

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/")
Run Code Online (Sandbox Code Playgroud)


Joe*_*Joe 5

尝试这个:

fileHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("/absolute/path/static")))
http.Handle("/static/", fileHandler)
Run Code Online (Sandbox Code Playgroud)