Noè Murr
Noè Murr

Reputation: 616

Go Gorilla mux subrouter with static files

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)

Upvotes: 1

Views: 1886

Answers (1)

chris
chris

Reputation: 4351

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

Upvotes: 6

Related Questions