dongyou2714 2018-06-24 13:49 采纳率: 0%
浏览 57
已采纳

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

Problem

Hello, I want to create a web server that presents 2 pages and 2 static directory using a router and a subrouter.

I cannot understand why the static directory served by the router is shown while the static server handled by the subrouter is not working.

The code,the file system scheme and the web pages: shown and wanted are shown below.

File system scheme

ProjectFolder/
    testFile
    test.go

Code

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

Pages that I want in the web server

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)

Pages that I have in the web server

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条回答 默认 最新

  • douliu1092 2018-06-24 15:28
    关注

    Try changing the sub fileserver line to (include the sub path in the StripPrefix call)

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

    The code below works for me

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突