HOw I can serve static files in subroutes Gorilla mux?

1,092 views
Skip to first unread message

MIhail Rbk

unread,
Mar 23, 2016, 4:23:12 AM3/23/16
to Gorilla web toolkit
Good, thats is my qwestion

i have  a code


func MainRouter() *mux.Router {
    prefix := "/"
    adminus_prefix := "/adminus/"
    r := mux.NewRouter()
    publicSub := r.PathPrefix("/").Subrouter()
    publicus.Routers(publicSub, prefix)

    return r
}


+++++++++++++++++++++++++++++++++++++
//publicus.Routes

func Routers(router *mux.Router, prefix string) {

    router.HandleFunc("/", handlers.MainHandler)
    router.HandleFunc("/help", handlers.HelpHandler)
    router.HandleFunc("/company", handlers.CompanyHandler)
    router.HandleFunc("/documents", handlers.DocumentsHandler)
    router.HandleFunc("/addcomplaint", handlers.AddcomplaintHandler).Methods("POST")
    //вешаем контроллеры на каждый из суброутов
    router.PathPrefix("/").Handler(http.StripPrefix(prefix, http.FileServer(http.Dir("./static/"))))

}

thats is simple organisaton of route handlers
each handler render html templates  like this

============================================
///handlers.main handler
    "github.com/flosch/pongo2"
)

var maintlp = pongo2.Must(pongo2.FromFile("templates/index.html"))

func MainHandler(w http.ResponseWriter, request *http.Request) {
    fmt.Println("MainHandler")
    Session := utils.NewDbinstanse()
    notices := make([]documents.Notice, 0)
    Session.C("notice").Find(nil).Sort("-time").All(&notices)

    err := maintlp.ExecuteWriter(pongo2.Context{"notices": notices}, w)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

and in html i get static files from folder like this


============================================
///index.html
   <link rel="stylesheet" type="text/css" href="css/css.css">


its work fine in root directory, but if i want add in route something like this
router.HandleFunc("/help/bablala/vlavlavla", handlers.BlablaHandler)
i render html teemplate but for css and js files  i get 404 error
i think problem in thats string

router.PathPrefix("/").Handler(http.StripPrefix(prefix, http.FileServer(http.Dir("./static/"))))
how i can fix it?

Matt Silverlock

unread,
Mar 23, 2016, 10:40:49 AM3/23/16
to Gorilla web toolkit
You are using relative links in your HTML.

Change:    <link rel="stylesheet" type="text/css" href="css/css.css">
To:    <link rel="stylesheet" type="text/css" href="/css/css.css">

MIhail Rbk

unread,
Mar 24, 2016, 4:44:15 AM3/24/16
to Gorilla web toolkit
this solution works for urls like /blablabla/blablabla))
thanks )
its very simple problem, but not obvious

среда, 23 марта 2016 г., 20:40:49 UTC+6 пользователь Matt Silverlock написал:
Reply all
Reply to author
Forward
0 new messages