带有静态文件的Gorilla Mux子路由器

时间:2018-06-24 13:49:22

标签: http go gorilla

问题

您好,我想使用路由器和子路由器创建一个显示2个页面和2个静态目录的Web服务器。

我不明白为什么当子路由器处理的静态服务器不工作时,为什么显示路由器提供的静态目录。

下面显示了所需的代码,文件系统方案和网页。

文件系统方案

ProjectFolder/
    testFile
    test.go

代码

package main

import (
    "github.com/gorilla/mux"
    "net/http"
)

func index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Index"));
}

func main () {
    r := mux.NewRouter()
    sub := r.PathPrefix("/sub").Subrouter()
    r.HandleFunc("/", index)
    r.Handle("/static", http.StripPrefix("/static", http.FileServer(http.Dir("./"))))
    sub.Handle("/static", http.StripPrefix("/static", http.FileServer(http.Dir("./"))))
    sub.HandleFunc("/", index)

    http.ListenAndServe(":8080", r)
}

我想要在Web服务器中的页面

http://localhost:8080/ ----> (index)
http://localhost:8080/static ---> (presentation of the file systemfolder)
http://localhost:8080/sub/ ---> (index)
http://localhost:8080/sub/static ---> (presentation of the file system folder)

我在Web服务器中拥有的页面

http://localhost:8080/ ----> (index)
http://localhost:8080/static ---> (presentation of the file system folder)
http://localhost:8080/sub/ ---> (index)
http://localhost:8080/sub/static ---> (404 page not found)

1 个答案:

答案 0 :(得分:4)

尝试将子文件服务器行更改为(在StripPrefix调用中包括sub路径)

sub.Handle("/static", http.StripPrefix("/sub/static", http.FileServer(http.Dir("./"))))

下面的代码对我有用

package main

import (
    "net/http"

    "github.com/gorilla/mux"
)

func index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Index"))
}

func main() {
    r := mux.NewRouter()
    r.Handle("/static", http.StripPrefix("/static", http.FileServer(http.Dir("./"))))
    r.HandleFunc("/", index)

    sub := r.PathPrefix("/sub").Subrouter()
    sub.Handle("/static", http.StripPrefix("/sub/static", http.FileServer(http.Dir("./"))))
    sub.HandleFunc("/", index)

    http.ListenAndServe(":8080", r)
}