小编Noè*_*urr的帖子

Go Gorilla mux subrouter with static files

问题

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

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

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

文件系统方案

ProjectFolder/
    testFile
    test.go
Run Code Online (Sandbox Code Playgroud)

代码

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

我想要在 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)
Run Code Online (Sandbox Code Playgroud)

我在 Web 服务器中的页面 …

http go gorilla

1
推荐指数
1
解决办法
1198
查看次数

标签 统计

go ×1

gorilla ×1

http ×1