Go Gorilla mux subrouter со статическими файлами - PullRequest
0 голосов
/ 24 июня 2018

Задача

Здравствуйте, я хочу создать веб-сервер, который представляет 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 Ответ

0 голосов
/ 24 июня 2018

Попробуйте изменить строку вспомогательного файлового сервера на (включая путь 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)
}
...