Подключение CSS к HTML с Go linux
Проблемы с подключением css к проекту. В HTML у меня:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- Стили сайта -->
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container">
<img class="imgstars" src="https://thumb.tildacdn.com/tild3531-3462-4931-b561-653663313033/-/format/webp/image.png">
<h1 class="h1">Hello</h1>
<h1 class="h1">Hi</h1>
</div>
</body>
</html>
А CSS:
body {
background-color: blue;
}
.container {
width: 100%;
}
h1 {
color: green;
}
Код на Go:
import (
"html/template"
"net/http"
)
var tpl *template.Template
func home_page(w http.ResponseWriter, r *http.Request) {
tpl.Execute(w, nil)
}
func handleRequest() {
http.HandleFunc("/", home_page)
http.ListenAndServe(":8080", nil)
}
func main() {
tpl, _ = tpl.ParseFiles("index.html")
handleRequest()
}
У меня не меняется ни текст ни фон.
Ответы (1 шт):
Автор решения: Pak Uula
→ Ссылка
Вы обрабатываете только запросы GET /, запросы GET /style.css ваш сервер отвергает (вероятнее всего, возвращает 404). Поэтому браузер не отрисовывает стили, он о них просто не знает.
Варианты решения:
Статический сервер, отдаёт файлы из определённой папки, включая
index.htmlиstyle.css:http.FileServerДобавьте обработчик для
style.css. Для этого можно использоватьServeMux, чтобы обслуживать несколько эндпоинтов.
Например, можно сделать вот так:
package main
import (
"io"
"net/http"
"os"
)
func main() {
runServer()
}
func runServer() {
indexHtml := NewServeFile("text/html", "site/index.html")
stylesCss := NewServeFile("text/css", "site/styles.css")
mux := http.NewServeMux()
mux.Handle("/", indexHtml)
mux.Handle("/index.html", indexHtml)
mux.Handle("/styles.css", stylesCss)
http.ListenAndServe(":8080", mux)
}
// Передаёт один статический файл
type ServeFile struct {
contentType string
fileName string
}
func NewServeFile(contentType, fileName string) *ServeFile {
return &ServeFile{
contentType: contentType,
fileName: fileName,
}
}
func (sf *ServeFile) ServeHTTP(w http.ResponseWriter, r *http.Request) {
file, err := os.Open(sf.fileName)
if err != nil {
http.Error(w, "No such file", http.StatusNotFound)
return
}
defer file.Close()
w.Header().Add("Content-Type", sf.contentType)
io.Copy(w, file)
}