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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化