feat: add .html extension
All checks were successful
Build and Push / build-and-push (push) Successful in 22s
All checks were successful
Build and Push / build-and-push (push) Successful in 22s
This commit is contained in:
56
main.go
56
main.go
@@ -5,23 +5,67 @@ import (
|
|||||||
"io/fs"
|
"io/fs"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed public/*
|
//go:embed public/*
|
||||||
var publicFS embed.FS
|
var publicFS embed.FS
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Получаем подпапку 'public' из embed.FS
|
// Используем подпапку 'public' из embed.FS
|
||||||
pub, err := fs.Sub(publicFS, "public")
|
content, err := fs.Sub(publicFS, "public")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Создаем файловый сервер с корнем в подпапке public
|
// Создаем файловый сервер с нашим обработчиком расширений
|
||||||
fileServer := http.FileServer(http.FS(pub))
|
fileServer := http.FileServer(neuterFileSystem{http.FS(content)})
|
||||||
|
|
||||||
http.Handle("/", fileServer)
|
http.Handle("/", fileServer)
|
||||||
|
log.Println("Server started on :8080")
|
||||||
log.Println("Server starting on :8080")
|
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// neuterFileSystem предотвращает листинг директорий и добавляет .html к URL без расширения
|
||||||
|
type neuterFileSystem struct {
|
||||||
|
fs http.FileSystem
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n neuterFileSystem) Open(path string) (http.File, error) {
|
||||||
|
f, err := n.fs.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
f, err = n.fs.Open(path + ".html")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем, не директория ли это
|
||||||
|
s, err := f.Stat()
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.IsDir() {
|
||||||
|
// Пробуем открыть index.html в директории
|
||||||
|
index := filepath.Join(path, "index.html")
|
||||||
|
if _, err := n.fs.Open(index); err != nil {
|
||||||
|
closeErr := f.Close()
|
||||||
|
if closeErr != nil {
|
||||||
|
log.Println(err)
|
||||||
|
|
||||||
|
return nil, closeErr
|
||||||
|
}
|
||||||
|
log.Println(err)
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user