Использовал этот код для статических файлов:
func main() {
http.Handle("/", http.FileServer(http.Dir("./files")))
http.ListenAndServe(":5000", nil)
}
Потом появилась необходимость расширить приложение. Добавил роутинг:
package main
import (
"net/http"
"github.com/gorilla/mux"
"fmt"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/files/", FileServer)
http.ListenAndServe(":5000", router)
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Привет. Это главная страница")
}
func FileServer(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.FileServer(http.Dir("./files"))
}
Но статические файлы не грузятся. Нужно, чтобы по ссылке site/files/css/my.css
грузился соответственный файл.
Как мне и роутинг сделать, и файл-сервер чтоб был?
Ответ
Спасибо D-side.
router := mux.NewRouter()
s := http.StripPrefix("/files/", http.FileServer(http.Dir("./files/")))
router.HandleFunc("/", Index)
router.PathPrefix("/files/").Handler(s)
http.Handle("/", router)
http.ListenAndServe(":5000", nil)