Проблемы с подключение статических файлов к HTML с gorilla/mix Go
В HTML я подключил css:
<link rel="stylesheet" href="../static/css/reset.css">
<link rel="stylesheet" href="../static/css/style.css">
Вот код в main.go:
import (
"html/template"
"log"
"net/http"
"github.com/gorilla/mux"
)
var templates *template.Template
func main() {
templates = template.Must(template.ParseGlob("ui/html/*.html"))
log.Println("Server will start at http://localhost:8080/")
r := mux.NewRouter()
r.HandleFunc("/", home).Methods("GET")
r.HandleFunc("/forum", forum).Methods("GET")
r.HandleFunc("/adviсe", adviсe).Methods("GET")
http.ListenAndServe(":8080", r)
fs := http.FileServer(http.Dir("./ui/static/"))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
log.Fatal(http.ListenAndServe(":8080", r))
}
И код в handlers.go:
func home(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "home_page.html", r)
}
func forum(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "forum.html", r)
}
func adviсe(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "adviсe.html", r)
}
Сервер не видит css
Ответы (1 шт):
Автор решения: Максим
→ Ссылка
вместо:
fs := http.FileServer(http.Dir("./ui/static/"))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
я вставил:
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./ui/static/")))
r.PathPrefix("/static/").Handler(s)
И стили работают Вот моя исправленная функция main:
templates = template.Must(template.ParseGlob("ui/html/*.html"))
log.Println("Server will start at http://localhost:8080/")
r := mux.NewRouter()
r.HandleFunc("/", home).Methods("GET")
r.HandleFunc("/forum", forum).Methods("GET")
r.HandleFunc("/adviсe", adviсe).Methods("GET")
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./ui/static/")))
r.PathPrefix("/static/").Handler(s)
http.ListenAndServe(":8080", r)
log.Fatal(http.ListenAndServe(":8080", r))