72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package main
|
||
|
||
import (
|
||
"embed"
|
||
"io/fs"
|
||
"log"
|
||
"net/http"
|
||
"path/filepath"
|
||
)
|
||
|
||
//go:embed public/*
|
||
var publicFS embed.FS
|
||
|
||
func main() {
|
||
// Используем подпапку 'public' из embed.FS
|
||
content, err := fs.Sub(publicFS, "public")
|
||
if err != nil {
|
||
log.Fatal(err)
|
||
}
|
||
|
||
// Создаем файловый сервер с нашим обработчиком расширений
|
||
fileServer := http.FileServer(neuterFileSystem{http.FS(content)})
|
||
|
||
http.Handle("/", fileServer)
|
||
log.Println("Server started on :8080")
|
||
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
|
||
}
|