使用Gorilla工具包提供带有根URL的静态内容



我正在尝试使用大猩猩工具包的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)
}

目录结构为:

...
main.go
static
  | index.html
  | js
     | <js files>
  | css
     | <css files>

Javascript和CSS文件在index.html中引用如下:

...
<link rel="stylesheet" href="css/redmond/jquery-ui.min.css"/>
<script src="js/jquery.min.js"></script>
...

当我在浏览器中访问http://localhost:8100时,index.html内容发送成功,但是jscss的url都返回404。

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

我想你可能在寻找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/")

试试这个:

fileHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("/absolute/path/static")))
http.Handle("/static/", fileHandler)

这将服务于文件夹标志内的所有文件,以及在根目录下服务index.html。

使用

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

最新更新