代码之家  ›  专栏  ›  技术社区  ›  Noè Murr

带有静态文件的Gorilla mux子程序

  •  1
  • Noè Murr  · 技术社区  · 7 年前

    您好,我想创建一个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)
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   chris    7 年前

    sub stripPrefix调用中的路径)

    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)
    }
    
    推荐文章