http - 带有静态文件的 Go Gorilla mux 子路由器

标签 http go gorilla

问题

你好,我想创建一个 Web 服务器,它使用一个路由器和一个子路由器来呈现 2 个页面和 2 个静态目录。

我无法理解为什么在子路由器处理的静态服务器不工作时显示路由器提供的静态目录。

代码、文件系统方案和网页:显示和想要的如下所示。

文件系统方案

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

我想要在网络服务器中的页面

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)

我在网络服务器上的页面

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)

最佳答案

尝试将子文件服务器行更改为(在 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)
}

关于http - 带有静态文件的 Go Gorilla mux 子路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51010538/

相关文章:

python - 如何计算推文的大小或数量?

swift - 尝试访问 Alamofire 中的错误代码

javascript - 如何作为客户端连接 Node.js 和 Android?

go - r.Handle : missing method ServeHTTP error 参数中的 http.Handler 值

go - 如何使用 Gorilla Mux 在 GET 请求中进行可选查询?

r - Httr header 在数字文字中返回无效字符 '-'

dictionary - 如何比较 map 的身份或本例中发生了什么?

go - Go安装程序未安装“开始”菜单组而不是“科学”

go - 以下实现是否使我的代码并行?

reactjs - 在 Gorilla Mux : 403 error on POST request 中配置 CORS