Serving static content with a root URL with the Gorilla toolkit

后端 未结 5 2104
礼貌的吻别
礼貌的吻别 2020-12-12 18:42

I am attempting to use the Gorilla toolkit\'s mux package to route URLs in a Go web server. Using this question as a guide I have the following Go code:

fu         


        
5条回答
  •  执笔经年
    2020-12-12 19:43

    After a lot of trial and error, both above answers helped me in coming up with what worked for me. I have static folder in web app's root directory.

    Along with PathPrefix I had to use StripPrefix for getting route to work recursively.

    package main
    
    import (
        "log"
        "net/http"
        "github.com/gorilla/mux"
    )
    
    func main() {
        r := mux.NewRouter()
        s := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
        r.PathPrefix("/static/").Handler(s)
        http.Handle("/", r)
        err := http.ListenAndServe(":8081", nil)
    }
    

    I hope it helps somebody else having problems.

提交回复
热议问题