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

时间:2013-04-05 12:41:29

标签: web-applications go mux

我正在尝试使用Gorilla工具包的mux package来路由Go Web服务器中的URL。使用this question作为指南,我有以下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>

index.html中引用了Javascript和CSS文件,如下所示:

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

当我在网络浏览器中访问http://localhost:8100时,index.html内容已成功发送,但是,所有jscss网址都会返回404。

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

5 个答案:

答案 0 :(得分:74)

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

答案 1 :(得分:38)

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

我希望它有助于其他人遇到问题。

答案 2 :(得分: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/")

答案 3 :(得分:4)

试试这个:

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

答案 4 :(得分:-1)

这为文件夹标志内的所有文件提供服务,并在根目录下提供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))
}